Search code examples
cindexingindexoutofboundsexceptionbubble-sort

Possible mistake in bubble sort c program


I was reading the book "Computer Organization and Design" by Patterson and Hennesy (5th Edition) and found this bubble sort code:

void sort (int v[], int n)
{
    int i,j;
    for (i=0; i<n; i+=1) {
        for (j = i-1; j>=0 && v[j] > v[j+1]; j+=1) {
            swap(v,j);
        }
    }
}

void swap (int v[], int k) {
    int temp;
    temp = v[k];
    v[k] = v[k+1];
    v[k+1] = temp;
}

I don't understand how this function would sort an array. Especially if the first element of the array is also the largest, it seems to me that the index j would go out of bounds. Running the code and printing the indices confirmed this.

This is the code I used:

#include <stdio.h>

void swap (int v[], int k) {
    int temp;
    temp = v[k];
    v[k] = v[k+1];
    v[k+1] = temp;
}

void sort (int v[], int n)
{
    int i,j;
    for (i=0; i<n; i+=1) {
        printf("%d \n", i);
        for (j = i-1; j>=0 && v[j] > v[j+1]; j+=1) {
            printf("%d, %d \n", i, j);
            swap(v,j);
        }
    }
}

int main() {
    int x[3] = {5,1,2};
    int N = 3;

    sort(x, N);
    for(int i = 0; i < 3; i++) {
        printf("%d ", x[i]);
    }
    return 0;
}

This was the result:

/Users/mauritsdescamps/Desktop/test/cmake-build-debug/test
0 
1 
1, 0 
1, 1 
1, 2 
1, 3 
1, 4 
2 
2, 1 
2, 2 
2, 3 

Process finished with exit code 6

Is there something I am forgetting? If not, I think there must be a mistake in the second loop condition. I have seen other implementations of the algorithm but I want to know how to get this approach to work.


Solution

  • I've tried this code, too. I have compiled it with GCC and somehow it worked for me (the exit status of the program was 0 and the array was sorted correctly). But I also think that their is a problem with the second loop. I would change the j+= 1 instruction into j-=1. Otherwise the second loop could end in an infinite loop. Additionally I would change the i=0 instruction in the first loop into a i=1 instruction, because it would end in an unnecessary iteration.