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;
}
}
Change this code snippet
to
Take into account that there is no sense to initialize defined variables
because they are overwritten in the followed statements.