【问题标题】:Why does my sort print out multiple lists?为什么我的排序会打印出多个列表?
【发布时间】: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


【解决方案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]);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-08
    相关资源
    最近更新 更多