Search code examples
cbubble-sort

Why does my sort print out multiple lists?


I tried doing this bubble sort, and when I run it, it prints out the original, and 2 unsorted "sorted" lists, then finally the actual sorted list. How can I get rid of the extra "sorts'?

#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;
}

Solution

  • Your print statement is inside of the while loop, so you are printing on each iteration. You need to move the print statement outside of the while loop, so that it prints once sorting is complete.

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