C中的冒泡排序数组错误:第二个整数始终为零

Bubble Sorted array Error in C: Second integer is Always Zero

我写了一个程序,对长度不超过20个整数的数组进行冒泡排序,其内容由用户决定。我遇到的问题是,当打印排序数组时,数组中的第二个整数始终为 0,导致排序数组中的最大整数无法打印。下面是我的代码:

#include <stdio.h>

int main()
{
  int array[20];
  int n;
  int c;
  int d;
  float swap;
  printf("Please enter how many numbers you want to sort (up to 20):\n\t");
  scanf("%d", &n);
  if (n >= 2)
  {
    for (c = 0; c < n; c++)
    {
      printf("Please enter the next number:\n\t");
      scanf("%d", &array[c]);
    }
    for (c = 0; c < (n - 1); c++)
    {
      for (d = 0; d < (n - c); d++)
      {
        if (array[d] > array[d + 1])
        {
          swap = array[d];
          array[d] = array[d + 1];
          array[d + 1] = swap;
        }
      }
    }
    for (c = 0; c < n; c++)
    {
      printf("%d\n", array[c]);
    }
    printf("Here are the results in ascending order:\n");
  }
  else
  {
    printf("Since you have fewer than two numbers, they are already sorted!\n");
  }
  return 0;
}
for (d = 0; d < (n - c); d++)

这是不对的。想想六个数字(数组元素零到五)会发生什么。

第一次通过交换循环,n 将为 6,而 c 将为零。这意味着 d 将取零到五的值。

不幸的是,您正在交换索引 dd + 1,后者将是任意数据(索引 6),因为您没有填写它。

由于您没有看到最后一位数字,而是看到了零,因此很可能(a) 元素 beyond您要填充的最后一个设置为零。这将导致交换代码交换它和您的最后一个元素,从而导致您看到的结果:

0   1   2   3   4   5   6   7   8   9 <-- indexes
<--- you entered --->   remainder -->
3   1   4   1   5   9   0   0   0   0 <-- data
                    \___/
                        \
                         these will swap

应该使用的是:

for (d = 0; d < n - c - 1; d++)

看到(b):

1 0 1 3 4 5

和:

1 1 3 4 5 9

(a) 可能, 但绝不保证。由于 array 是局部变量,未初始化元素的值是任意的。

如果您的代码有时能正常工作,那是因为这个 - 您可以通过确保数组元素全部初始化为零来获得可重复的失败:

int array[20] = {0};

然后,由于它是可重现的,您可以进行此答案中给出的更改来修复它。


(b) 顺便说一句,在这种情况下 0 没有一直冒到底部的原因是因为它是 newly 在第一遍中引入到数据中。这意味着比完全排序数据所需的遍数要少一次。