【发布时间】:2014-12-16 03:51:27
【问题描述】:
我尝试进行这种冒泡排序,当我运行它时,它会打印出原始列表和 2 个未排序的“排序”列表,最后是实际的排序列表。我怎样才能摆脱多余的“排序”?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 9
int main(void)
{
int ray[SIZE]= {8,1,5,8,1,2,4,5,9};
int i, temp, swapped;
for( i = 0; i < SIZE; i++){
ray[i] ;
}
printf("Red ID\n", ray[i]);
for( i = 0; i < SIZE; i++){
printf(" %d\n", ray[i]);
}
while(1){
swapped = 0; // when swapped = 1, loop repeats, when 0, it ends
for( i=0; i<SIZE-1; i++){ //the -1 ends it at the second to last digit in the array
if( ray[i] > ray[i + 1]){
temp = ray[i];
ray[i] = ray[i + 1]; // this whole block does the swapping
ray[i + 1] = temp;
swapped=1;
}
}
if(swapped==0){
break;
}
printf("\n Sorted Red ID\n");
for(i=0; i<SIZE; i++){
printf(" %d\n", ray[i]);
}
}
return 0;
}
【问题讨论】:
-
您希望对声明
ray[i] ;做什么? -
你确实打印in the loop,也许你应该在outside循环?
-
这什么都不做: for( i = 0; i
-
这一行:printf("Red ID\n", ray[i]);将始终在数组末尾打印一个。
-
此代码:printf("\n 已排序的红色 ID\n"); for(i=0; i
标签: c bubble-sort