输入一个数组:
ary[] = [11 12 13 14 15 16 17 18 19 20 11 12 13 14 15 16 17 18 19 20 11 12 13 14 15 16 17 18 19 20 11 12 13 14 -1] (the negative one signifies that it is the end of the array)
输入尺寸:
size = 34
我需要重新排列该数组,使其按顺序排列。下面是我的代码:
int x;
int numpasses;
int temp;
for(numpasses = 1; numpasses < size; numpasses++)
{
for(x = 0; x < size - numpasses; x++)
{
if(ary[x] > ary[x + 1] && ary[x] != ary[size - 1])
{
temp = ary[x];
ary[x] = ary[x + 1]; //THIS PORTION SWITHCHES TWO ADJECENT VALUES TO MAKE ARRAY SEQUENTIAL
ary[x + 1] = temp;
}
}
int a;
for(a = 0; a < size; a++)
{
printf("%d ", ary[a]);
}
}
这会打印数字,如下所示:
11 11 12 12 13 13 14 14 15 15 16 16 17 17 18 18 19 19 20 11 12 13 14 15 16 17 18 19 20 11 12 13 14
最佳答案
更换线路
if(ary[x] > ary[x + 1] && ary[x] != ary[size - 1])
由
if(ary[x] > ary[x + 1] )
对我来说效果很好。
我会让你找出原因。
附注。
请添加
printf("\n");
打印数组后。它使得在外循环结束时看到的结果更加清晰。
关于c - 为什么我的代码没有按顺序打印整个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23281742/