我输入的任何值都会得到错误的输出,例如,如果我输入了5,4,3,2,1,则输出为1,1,1,1。。。我在bubble sort函数中使用了气泡排序算法。。。并将数组A传递给函数,但输出仅包含我输入的最后一个值。

#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++)

10-04 11:55
查看更多