Home > Back-end >  Why does my sorting function output garbage values?
Why does my sorting function output garbage values?

Time:10-18

  • I'm working on a bubble sort but the length is completely off which starts printing garbage values like 0,1,2
  • I've tried manipulating my conditional inside my for loop but it still outputs the garbage values
    
void bubbleSort(int array[], int len){
    int temp;
    int counter = -1; 
    printf("\n");
    while(counter != 0){
        counter = 0;
        for (int i = 0; i < len; i  ) {
            //compare two ints swich the greater value to the right
            if (array[i] > array[i   1]){
                temp = array[i   1];
                array[i   1] = array[i];
                array[i] = temp;
                counter  ;
                //increment counter
            }
        }
    }
    for (int i = 0; i <= len; i  ) {
        printf("%i ", array[i]);
    }
    printf("\nBubble Sort Completed\n");
}

int main(void){
    int a[] = {1, 2, 4, 5, 7 ,6, 8, 3, 9};
    int b[] = {10, 20, 40, 54, 23, 23, 12};
    size_t a_length =  sizeof(sizeof(a)/sizeof(a[0]));
    size_t b_length =  sizeof(sizeof(b)/sizeof(b[0]));
    bubbleSort(a, a_length);
    bubbleSort(b, b_length);
}

My output usually looks like this

1 2 3 4 5 6 7 8 9 Bubble Sort Completed

0 1 10 12 20 23 23 40 54 Bubble Sort Completed

  1. Also just a little curious as to why the length of array b is equal to 8? Shouldn't the value be 7?

CodePudding user response:

At least these problems:

Compare eventually accesses outside array bounds with array[i 1] leading to undefined behavior (UB). Anything may happen with UB.

    // Alternative code
    // for (int i = 0; i < len; i  ) {
    for (int i = 1; i < len; i  ) {
        // if (array[i] > array[i   1]){
        if (array[i-1] > array[i]){
            temp = array[i];
            array[i] = array[i-1];
            array[i-1] = temp;
            counter  ;
        }
    }

... and ...

// for (int i = 0; i <= len; i  ) {
for (int i = 0; i < len; i  ) {
    printf("%i ", array[i]);
}

... and ... @Weather Vane

Wrong size calculation.

//size_t a_length =  sizeof(sizeof(a)/sizeof(a[0]));
//size_t b_length =  sizeof(sizeof(b)/sizeof(b[0]));
size_t a_length =  sizeof a / sizeof a[0];
size_t b_length =  sizeof b / sizeof b[0];

Also consider using same type in array indexing

// void bubbleSort(int array[], int len){
void bubbleSort(int array[], size_t len){

  size_t temp, counter;
  ...
  • Related