我正在制作一个使用动态内存分配的程序,可以重新排列数组的元素。但它给出了错误的结果。
这是我的代码:
#include<stdio.h>
#include<stdlib.h>
int bubble_sort(int n,int *ar)
{
int i=0,j=0,temp;
for(i; i<n;i++)
{
for(j; j<n-i-1;j++)
{
if(*(ar + j)>*(ar + j + 1))
{
temp = *(ar + j);
*(ar + j) = *(ar + j + 1);
*(ar + j + 1) = temp;
}
}
}
}
main()
{
int n,i;
printf("Enter the size of the array : ");
scanf("%d",&n);
int *arr1 = (int *)calloc(n,sizeof(int));
printf("Enter the elements of first array : \n");
for(i=0;i<n;i++)
{
scanf("%d",(arr1+i));
printf("\n");
}
bubble_sort(n,arr1);
printf("After sorting, array is : \n");
for(i=0;i<n;i++)
{
printf("%d\t",*(arr1 + i));
}
}
它给出的输出只是我作为数组元素输入的一组随机数字。
例如,如果我输入数组元素的数量为 6,然后输入元素为
7, 8, 9, 5, 6, 4
那么输出是
7, 8, 5, 6, 4, 9
最佳答案
每次通过外循环都需要从0开始j,改变
for(j; j<n-i-1;j++)
至
for(j=0; j<n-i-1; j++)
一般来说,最好在 for 循环中初始化计数器变量,以避免对其范围产生混淆并避免出现此类错误。所以就算了
int i=0;
for(i; i<n;i++)
最好写成
int i;
for(i=0; i<n;i++)
甚至更好(对于现代 C 编译器)
for (int i = 0; i < n; i++)
关于c - 冒泡排序不适用于 C 中的动态内存分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48718296/