-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinsertion_sort.c
50 lines (40 loc) · 1.06 KB
/
insertion_sort.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include <stdio.h>
void insertionSort(int *arr, int n) {
// i is pointing to number we want to 'insert' into sorted array
for (int i = 1; i < n; i++) {
// Value of the number in position i
int key = arr[i];
// arr[0 ... j] is the sorted part of the array
int j = i - 1;
// Move elements of the sorted array if they are larger than our key
while (j >= 0 && arr[j] > key) {
arr[j+1] = arr[j];
j--;
}
// Insert our number in position i
arr[j+1] = key;
}
}
/**
* Prints out an array to std out.
*/
void printArray(int *arr, int n) {
int i;
for (i = 0; i < n; i++) {
printf("%d", arr[i]);
if (i < n - 1) {
printf(", ");
}
}
printf("\n\n");
}
int main() {
int input_array[] = {9, 8, 2, 4, 10, 5, 7, 6, 3, 1, 7};
int size = 10;
printf("Before:\n");
printArray(input_array, size);
insertionSort(input_array, size);
printf("After:\n");
printArray(input_array, size);
return 0;
}