【发布时间】:2014-02-25 19:39:11
【问题描述】:
我正在尝试在 C 中实现冒泡排序,并且已经走到了这一步,但它的排序也不正确。
#include<stdio.h>
int main()
{
int n, i, j, a[5], b, temp;
printf("Enter the number of elements to be sorted\n");
scanf("%d", &n);
for(i = 0; i < n; ++i)
{
printf("%d - Enter the elements - ", i);
scanf("%d", &a[i]);
}
for(i = 0; i < n; ++i)
{
for(j = 0; j < n+1; ++j)
{
if(a[i] > a[i+1])
{
temp = a[i];
a[i] = a[i+1];
a[i+1] = temp;
}
}
}
for (i = 0; i < n; ++i)
{
printf("%d\n", a[i]);
}
return 0;
}
输入
2
12
1
13
输出
2
1
12
13
我错过了什么?
【问题讨论】:
-
仅供参考,您的程序有一个重大缺陷。您询问用户他们将输入多少个元素,但您在此之前初始化了您的数组。如果有人输入大于 5 的数字,这可能会导致索引越界异常。干杯。
-
我已经用解释更新了我的答案。我希望你也解决我在之前的评论中提到的问题。干杯。