C Program for Recursive Insertion Sort

CServer Side ProgrammingProgramming

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[0] to arr[i].

Let’s take an example to understand the algorithm

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

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

[7, 34, 12, 90, 51]

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

[7, 12, 34, 90, 51]

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

[7, 12, 34, 90, 51]

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

[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[0]);
   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
raja
Published on 17-Jul-2020 16:07:42
Advertisements