gpt4 book ai didi

c - 为什么我的排序会打印出多个列表?

转载 作者:太空宇宙 更新时间:2023-11-03 23:48:41 25 4
gpt4 key购买 nike

我尝试进行这种冒泡排序,当我运行它时,它会打印出原始列表和 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;
}

最佳答案

您的 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]);
}

关于c - 为什么我的排序会打印出多个列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26477937/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com