【发布时间】:2011-09-18 16:40:05
【问题描述】:
我在 C 中制作了这个冒泡排序算法。它在 DM 中运行良好,但在 gcc 中执行时,输出不正确。
#include <stdio.h>
int i,j;
void BubbleSort(int*a, int n) //to sort the numbers
{
int temp;
for(i=0; i<n;i++)
for(j=n; j>i;j--)
if (a[j]<a[j-1])
{
temp=a[j];
a[j]=a[j-1];
a[j-1]=temp;
}
}
void Display(int * a, int n) //to display
{
printf("\nThe sorted numbers are:\n");
for(i=0;i<n;i++)
{
printf("%d, ",a[i]);
}
}
int main()
{
int a[50],n,choice;
printf("\nEnter no. of elements to sort: (max. 50) ");
scanf("%d",&n);
printf("\nEnter the numbers : ");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
BubbleSort(a,n);
Display(a,n);
return 0;
} //End of main
输入:
5
2 1 5 3 4
DM 输出:
1, 2, 3, 4, 5,
GCC 输出:
1, 2, 3, 5, 4,
这是如何以及为什么会发生的?
【问题讨论】:
-
您是否尝试过在调试器中单步执行?还是打印变量的中间值?
-
您正在访问循环中数组的
(n+1)th元素:a[j]是a[5],而j从 5 变为i。但是一个有 5 个元素的数组,没有索引5。 -
在任何情况下使用全局变量
i和j都是令人震惊的(使用单字母全局变量的理由很少),而且当它只是一种方式时更是如此避免声明循环变量。 C99 允许您编写:for (int i = 0; ...)等。 -
这也是一个糟糕的UI,需要您统计要排序的项目数才能输入。计算机擅长计数。 (如果你必须告诉它每个文件中有多少行数据,你不会使用 Unix
sort命令!) -
@Keith:我一直使用
i和j;投诉不仅仅是关于名称,而是关于使用具有全球地位的名称。我明确地说C99;如果您的编译器不是 C99,那么它将不支持该符号。 (因为这个问题在 Ubuntu 上引用了 GCC,所以这不是问题,除非你通过强制 C89 模式来阻碍它。)我不愿评论“它们应该是static,所以在这个源文件之外看不到它们” ;我也不愿评论排序函数中temp的不必要的大范围。
标签: c gcc bubble-sort dm