在冒泡排序中得到错误的输出

Getting Wrong output in bubble sorting

我输入的任何值都得到错误的输出,例如,如果我输入了 5,4,3,2,1,输出是 1,1,1,1,1... 我已经使用函数 bubblesort 中的冒泡排序算法...并将数组 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]);
  }
}

我认为你很接近,但我怀疑你的问题出在这里:

int temp;
temp=A[j+1];
A[j]=A[j+1];
A[j]=temp;

我相信你想设置 temp=A[j] 以便以后可以设置 A[j+1] = temp 或类似的东西。

一个逻辑错误:

交换

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

使用此代码进行冒泡排序

   #include <stdio.h>

int main()
{
  int array[100], n, c, d, swap;

  printf("Enter Total Terms\n");
  scanf("%d", &n);

  printf("Enter %d Elements\n", 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("%d\n", array[c]);

  return 0;
}