c - 为什么我的代码没有按顺序打印整个数组

标签 c arrays for-loop

输入一个数组:

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/

相关文章:

c - 需要动态内存字节

javascript - 空数组的串联如何防止排序突变?

java - 从列表中删除第二项会导致 REST API 崩溃

objective-c - 在 C 中的结构中扩展数组

在迷你 shell 中挂起 2 管道函数时,无法将信息存储在全局变量中

arrays - Golang的 "cap"

javascript - 如何在 SQL 中替换 json 字符串中的数字数组?

arrays - bash 使用数组变量创建 for 循环

python - 如何修复 'RuntimeWarning: divide by zero encountered in double_scalars'

c - glDisplayFunc(RenderScene) 回调是否会在以下代码中导致竞争条件?