Algorithms_in_C 1.0.0
Set of algorithms implemented in C.
Loading...
Searching...
No Matches
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.
 
static void test ()
 Test function.
 
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}

◆ main()

int main ( int  argc,
const char *  argv[] 
)
54{
55 /* Intializes random number generator */
56 srand(time(NULL));
57 test();
58 return 0;
59}
static void test()
Test function.
Definition insertion_sort.c:36

◆ 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}
void insertionSort(int *arr, int size)
Insertion sort algorithm implements.
Definition insertion_sort.c:16
#define free(ptr)
This macro replace the standard free function with free_dbg.
Definition malloc_dbg.h:26
#define calloc(elemCount, elemSize)
This macro replace the standard calloc function with calloc_dbg.
Definition malloc_dbg.h:22
Here is the call graph for this function: