In C: negative numbers insertion sort

1.2k views Asked by At

I'm fairly new into programming and my teacher want me to implement insertion sort in C.

My code works, but not with negative numbers if I use it with negative numbers in my array I always get a segmentation fault:

void insertion_sort(int array[], int len) {
    int i       = 0;
    int j       = 1;
    signed int tmp     = array[0];

    for(i = 1; i < len; i++) {
        tmp = array[i];
        j = i - 1;

        if(j >= 0){
            while(tmp < array[j]) {
                array[j + 1] = array[j];
                j = j - 1;
            }
        }
      array[j + 1] = tmp;
    }
}
1

There are 1 answers

1
Vlad from Moscow On BEST ANSWER

Change this code snippet

    if(j >= 0){
        while(tmp < array[j]) {
            array[j + 1] = array[j];
            j = j - 1;
        }
    }

to

    while ( j >= 0 && tmp < array[j] ) {
            array[j + 1] = array[j];
            j = j - 1;
    }

Take into account that there is no sense to initialize defined variables

int i       = 0;
int j       = 1;
signed int tmp     = array[0];

because they are overwritten in the followed statements.