# C Program for Recursive Insertion Sort

CServer Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

66 Lectures 5.5 hours

Insertion sort is a sorting algorithm which is an in-place comparison-based algorithm.

The algorithm works by place element in their position in the sorted sub-array i.e. the sub-array preceding the element which is a sorted sub-array.

## Algorithm

Step1 − loop from 1 to n-1 and do −

Step2.1 − select element at position i, array[i].

Step2.2 − insert the element in its position in the sorted sub-array array to arr[i].

Let’s take an example to understand the algorithm

Array = [34, 7, 12, 90, 51]

For i = 1, arr = 7, placing in its positon in subarray arr - arr.

[7, 34, 12, 90, 51]

For i = 2, arr = 12, placing in its positon in subarray arr - arr.

[7, 12, 34, 90, 51]

For i = 3, arr = 90, placing in its positon in subarray arr - arr.

[7, 12, 34, 90, 51]

For i = 4, arr = 51, placing in its positon in subarray arr - arr.

[7, 12, 34, 54, 90]

Here, we will see how recursive insertion sort works. It works on a reverse basis i.e. we will recursively call the recursiveInsertionSort() function for sorting n-1 element array as compared to the current iteration. And then in this sorted array which will be returned by the function, we will insert the nth element at its position as in the sorted array.

Program for recursive insertion sort −

## Example

Live Demo

#include <stdio.h>
void recursiveInsertionSort(int arr[], int n){
if (n <= 1)
return;
recursiveInsertionSort( arr, n-1 );
int nth = arr[n-1];
int j = n-2;
while (j >= 0 && arr[j] > nth){
arr[j+1] = arr[j];
j--;
}
arr[j+1] = nth;
}
int main(){
int array[] = {34, 7, 12, 90, 51};
int n = sizeof(array)/sizeof(array);
printf("Unsorted Array:\t");
for (int i=0; i < n; i++)
printf("%d ",array[i]);
recursiveInsertionSort(array, n);
printf("\nSorted Array:\t");
for (int i=0; i < n; i++)
printf("%d ",array[i]);
return 0;
}

## Output

Unsorted Array: 34 7 12 90 51
Sorted Array: 7 12 34 51 90