【问题标题】:Getting Wrong output in bubble sorting在冒泡排序中得到错误的输出
【发布时间】:2015-07-28 12:18:56
【问题描述】:

我输入的任何值都得到错误的输出,例如,如果我输入了 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]);
  }
}

【问题讨论】:

  • A[j]=A[j+1]; 应该是A[j+1]=A[j];
  • 交换是这样完成的temp = A[j]; A[j] = A[j + 1]; A[j+1] = temp;
  • 要使冒泡排序不再依赖于固定的#define,请考虑传递要排序的数组的大小(即void bubblesort (int *a, size_t n)),并从函数中删除所有输出例程并将其放回原处在调用者中(即main())。 注意: 您的循环声明将(例如 for (i = 0; i &lt; (int)n; i++) )带有必要的强制转换以避免比较有符号和无符号值。 (n 应该是 size_t(无符号),因为它永远不会是负数)

标签: c arrays function sorting bubble-sort


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

    一个逻辑错误:

    交换

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

    【讨论】:

      【解决方案3】:

      将此代码用于冒泡排序

         #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;
      }
      

      【讨论】:

        猜你喜欢
        • 2016-01-19
        • 2023-04-07
        • 2016-02-18
        • 1970-01-01
        • 1970-01-01
        • 2021-06-05
        • 2021-10-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多