我尝试进行这种冒泡排序,当我运行它时,它打印出原始的,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;
}
答案 0 :(得分:1)
您的print
语句位于while
循环内,因此您将在每次迭代时打印。您需要将print
语句移到while
循环之外,以便在排序完成后打印它。
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]);
}