-
-
Notifications
You must be signed in to change notification settings - Fork 4.4k
/
Copy pathinsertion_sort.c
59 lines (56 loc) · 1.28 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
51
52
53
54
55
56
57
58
59
/**
* @file
* @brief [Insertion sort](https://en.wikipedia.org/wiki/Insertion_sort)
* algorithm implementation.
*/
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
/**
* Insertion sort algorithm implements
* @param arr array to be sorted
* @param size size of array
*/
void insertionSort(int *arr, int size)
{
for (int i = 1; i < size; i++)
{
int j = i - 1;
int key = arr[i];
/* Move all elements greater than key to one position */
while (j >= 0 && key < arr[j])
{
arr[j + 1] = arr[j];
j = j - 1;
}
/* Find a correct position for key */
arr[j + 1] = key;
}
}
/** Test function
* @returns None
*/
static void test()
{
const int size = rand() % 500; /* random array size */
int *arr = (int *)calloc(size, sizeof(int));
/* generate size random numbers from -50 to 49 */
for (int i = 0; i < size; i++)
{
arr[i] = (rand() % 100) - 50; /* signed random numbers */
}
insertionSort(arr, size);
for (int i = 0; i < size - 1; ++i)
{
assert(arr[i] <= arr[i + 1]);
}
free(arr);
}
int main(int argc, const char *argv[])
{
/* Intializes random number generator */
srand(time(NULL));
test();
return 0;
}