2020-07-31 05:04:22 +03:00
|
|
|
/**
|
|
|
|
* @file
|
|
|
|
* @brief [Insertion sort](https://en.wikipedia.org/wiki/Insertion_sort)
|
|
|
|
* algorithm implementation.
|
|
|
|
*/
|
|
|
|
#include <assert.h>
|
2017-03-23 17:15:17 +03:00
|
|
|
#include <stdio.h>
|
2020-04-24 03:45:45 +03:00
|
|
|
#include <stdlib.h>
|
2020-07-31 05:04:22 +03:00
|
|
|
#include <time.h>
|
2017-03-23 17:15:17 +03:00
|
|
|
|
2020-07-31 05:04:22 +03:00
|
|
|
/**
|
|
|
|
* Insertion sort algorithm implements
|
|
|
|
* @param arr array to be sorted
|
|
|
|
* @param size size of array
|
2018-11-08 10:37:38 +03:00
|
|
|
*/
|
2020-04-24 03:45:45 +03:00
|
|
|
void insertionSort(int *arr, int size)
|
|
|
|
{
|
2020-07-31 05:04:22 +03:00
|
|
|
for (int i = 1; i < size; i++)
|
2020-04-24 03:45:45 +03:00
|
|
|
{
|
2020-07-31 05:04:22 +03:00
|
|
|
int j = i - 1;
|
|
|
|
int key = arr[i];
|
2019-07-26 02:10:19 +03:00
|
|
|
/* Move all elements greater than key to one position */
|
2020-04-24 03:45:45 +03:00
|
|
|
while (j >= 0 && key < arr[j])
|
|
|
|
{
|
2019-07-26 02:10:19 +03:00
|
|
|
arr[j + 1] = arr[j];
|
|
|
|
j = j - 1;
|
2017-03-23 17:15:17 +03:00
|
|
|
}
|
2019-07-26 02:10:19 +03:00
|
|
|
/* Find a correct position for key */
|
|
|
|
arr[j + 1] = key;
|
2018-11-08 10:37:38 +03:00
|
|
|
}
|
|
|
|
}
|
2017-03-23 17:15:17 +03:00
|
|
|
|
2020-07-31 05:04:22 +03:00
|
|
|
/** Test function
|
|
|
|
* @returns None
|
|
|
|
*/
|
|
|
|
static void test()
|
2020-04-24 03:45:45 +03:00
|
|
|
{
|
2020-07-31 05:04:22 +03:00
|
|
|
const int size = rand() % 500; /* random array size */
|
|
|
|
int *arr = (int *)calloc(size, sizeof(int));
|
2019-07-26 02:10:19 +03:00
|
|
|
|
2020-07-31 05:04:22 +03:00
|
|
|
/* generate size random numbers from -50 to 49 */
|
|
|
|
for (int i = 0; i < size; i++)
|
2020-04-24 03:45:45 +03:00
|
|
|
{
|
2020-07-31 05:04:22 +03:00
|
|
|
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]);
|
2018-11-08 10:37:38 +03:00
|
|
|
}
|
2020-04-24 03:45:45 +03:00
|
|
|
free(arr);
|
2020-07-31 05:04:22 +03:00
|
|
|
}
|
|
|
|
int main(int argc, const char *argv[])
|
|
|
|
{
|
|
|
|
/* Intializes random number generator */
|
|
|
|
srand(time(NULL));
|
|
|
|
test();
|
2018-11-08 10:37:38 +03:00
|
|
|
return 0;
|
2017-03-23 17:15:17 +03:00
|
|
|
}
|