Insertion Sort

Explanation:

Code:

1
#include <stdio.h>
2
3
void insertionSort(int data[], int len){
4
5
for(int i = 0; i < len-1; i++){
6
for(int j = i + 1; j < len; j++) {
7
if(data[i] > data[j]){
8
int tmp = data[j];
9
for(int k = j; k > i; k--){
10
data[k] = data[k-1];
11
}
12
data[i] = tmp;
13
}
14
}
15
}
16
}
Copied!

Test code:

1
int main(void){
2
3
int data[] = { -1, 0, 8, -9, 7, -99};
4
5
int len = sizeof(data)/sizeof(data[0]);
6
insertionSort(data, len);
7
8
for (int t = 0; t < len; t++)
9
printf("data[%d] = %d \n", t, data[t]);
10
11
12
return 0;
13
}
Copied!
Copy link