From c385b4bfa9df3750f96e426cf013c27ead774304 Mon Sep 17 00:00:00 2001 From: PawanJaiswal08 <82941430+PawanJaiswal08@users.noreply.github.com> Date: Wed, 13 Oct 2021 15:09:56 +0530 Subject: [PATCH] Added Recursive Insertion Sort in C++ --- Recursive_Insertion_Sort.cpp | 61 ++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 Recursive_Insertion_Sort.cpp diff --git a/Recursive_Insertion_Sort.cpp b/Recursive_Insertion_Sort.cpp new file mode 100644 index 0000000..ff5fe7f --- /dev/null +++ b/Recursive_Insertion_Sort.cpp @@ -0,0 +1,61 @@ +// Recursive C++ program for insertion sort + +// TIME COMPLEXITY +// 1. Best complexity: n +// 2. Average complexity: n^2 +// 3. Worst complexity: n^2 + +#include +using namespace std; + +// Recursive function to sort an array using +// insertion sort +void insertionSortRecursive(int arr[], int n) +{ + // Base case + if (n <= 1) + return; + + // Sort first n-1 elements + insertionSortRecursive( arr, n-1 ); + + int last = arr[n-1]; + int j = n-2; + + while (j >= 0 && arr[j] > last) + { + arr[j+1] = arr[j]; + j--; + } + arr[j+1] = last; +} + +void display(int arr[], int n) +{ + for (int i=0; i < n; i++) + cout << arr[i] <<" "; +} + +int main() +{ + int n; + cout<<"Enter number of elements : "; + cin>>n; + + int arr[n]; + cout<<"Enter the array elements :\n"; + for(int i=0;i>arr[i]; + } + + cout<<"\nBefore Sort the array is :\n"; + display(arr,n); + + insertionSortRecursive(arr, n); + + cout<<"\nAfter Insertion Sort the array is :\n"; + display(arr, n); + + return 0; +}