Algorithms_in_C  1.0.0
Set of algorithms implemented in C.
insertion_sort.c File Reference

Insertion sort algorithm implementation. More...

#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
Include dependency graph for insertion_sort.c:

Functions

void insertionSort (int *arr, int size)
 Insertion sort algorithm implements. More...
 
static void test ()
 Test function. More...
 
int main (int argc, const char *argv[])
 

Detailed Description

Insertion sort algorithm implementation.

Function Documentation

◆ insertionSort()

void insertionSort ( int *  arr,
int  size 
)

Insertion sort algorithm implements.

Parameters
arrarray to be sorted
sizesize of array
17 {
18  for (int i = 1; i < size; i++)
19  {
20  int j = i - 1;
21  int key = arr[i];
22  /* Move all elements greater than key to one position */
23  while (j >= 0 && key < arr[j])
24  {
25  arr[j + 1] = arr[j];
26  j = j - 1;
27  }
28  /* Find a correct position for key */
29  arr[j + 1] = key;
30  }
31 }

◆ test()

static void test ( void  )
static

Test function.

Returns
None
37 {
38  const int size = rand() % 500; /* random array size */
39  int *arr = (int *)calloc(size, sizeof(int));
40 
41  /* generate size random numbers from -50 to 49 */
42  for (int i = 0; i < size; i++)
43  {
44  arr[i] = (rand() % 100) - 50; /* signed random numbers */
45  }
46  insertionSort(arr, size);
47  for (int i = 0; i < size - 1; ++i)
48  {
49  assert(arr[i] <= arr[i + 1]);
50  }
51  free(arr);
52 }
Here is the call graph for this function:
insertionSort
void insertionSort(int *arr, int size)
Insertion sort algorithm implements.
Definition: insertion_sort.c:16