forked from frhnafz/Awesome-Projects
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sort.c
46 lines (31 loc) · 997 Bytes
/
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
// The idea is to divide the array into two subsets – sorted subset and unsorted subset. Initially, a sorted subset consists of only one first element at index 0. Then for each iteration, insertion sort removes the next element from the unsorted subset, finds the location it belongs within the sorted subset and inserts it there. It repeats until no input elements remain.
#include <stdio.h>
void insertionSort(int arr[], int n)
{
for (int i = 1; i < n; i++)
{
int value = arr[i];
int j = i;
while (j > 0 && arr[j - 1] > value)
{
arr[j] = arr[j - 1];
j--;
}
arr[j] = value;
}
}
void printArray(int arr[], int n)
{
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
}
int main(void)
{
int arr[] = { 3, 8, 5, 4, 1, 9, -2 };
int n = sizeof(arr) / sizeof(arr[0]);
insertionSort(arr, n);
// print the sorted array
printArray(arr, n);
return 0;
}