对于我输入的任何值,我得到错误的输出,例如,如果我输入5,4,3,2,1,输出是1,1,1,1,1…我在函数bubblesort中使用了冒泡排序算法…并将数组A传递给函数,但输出仅包含i输入的最后一个值。
#include <stdio.h>
#define SIZE 5
void bubblesort(int A[]);
int main(void)
{
int A[SIZE]={0};
int i;
puts("Enter value to store it in integer");
for(i=0;i<SIZE;i++)
{
scanf("%d",&A[i]);
}
puts("");
bubblesort(A);
}
void bubblesort(int A[])
{
int i,j;
for(i=0;i<SIZE;i++)
{
for(j=0;j<4;j++)
{
if(A[j]>A[j+1])
{
int temp;
temp=A[j+1];
A[j]=A[j+1];
A[j]=temp;
}
}
}
for(i=0;i<SIZE;i++)
{
printf("%d ",A[i]);
}
}
逻辑错误:
交换 temp=A[j+1]; // stores A[j+1] in temp
A[j]=A[j+1]; // stores A[j+1] in A[j] - the value in A[j] is lost
A[j]=temp; // stores temp in A[j]
正确的方法是:
temp=A[j+1]; // stores A[j+1] in temp
A[j+1]=A[j]; // stores A[j] in A[j+1]
A[j]=temp; // stores temp in A[j]
两个建议:
将此:int temp;
移出for loop
。
改变:
for(j=0;j<4;j++)
:
for(j=0;j<i;j++)
我想你很接近了,但我怀疑你的问题在这里:
int temp;
temp=A[j+1];
A[j]=A[j+1];
A[j]=temp;
我相信您想设置temp=A[j]
,以便稍后可以设置A[j+1] = temp
或其他类似的内容。
使用冒泡排序代码
#include <stdio.h>
int main()
{
int array[100], n, c, d, swap;
printf("Enter Total Termsn");
scanf("%d", &n);
printf("Enter %d Elementsn", n);
for (c = 0; c < n; c++)
scanf("%d", &array[c]);
//bubble sort logic
for (c = 0 ; c < ( n - 1 ); c++)
{
for (d = 0 ; d < n - c - 1; d++)
{
if (array[d] > array[d+1]) /* use < For decreasing order */
{
swap = array[d];
array[d] = array[d+1];
array[d+1] = swap;
}
}
}
printf("ascending order:n");
for ( c = 0 ; c < n ; c++ )
printf("%dn", array[c]);
return 0;
}