-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathRecursive_Insertion_Sort.cpp
61 lines (48 loc) · 1.04 KB
/
Recursive_Insertion_Sort.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
// Recursive C++ program for insertion sort
// TIME COMPLEXITY
// 1. Best complexity: n
// 2. Average complexity: n^2
// 3. Worst complexity: n^2
#include <iostream>
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<n;i++)
{
cin>>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;
}