-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinsertion_sort.cpp
More file actions
50 lines (49 loc) · 928 Bytes
/
insertion_sort.cpp
File metadata and controls
50 lines (49 loc) · 928 Bytes
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
#include <iostream>
using namespace std;
void insert_iter(int a[], int x)
{
int key;
for (int i = 1; i < x; i++)
{
key =a[i];
int j =i-1;
while (j>=0 &&a[j]>key)
{
a[j+1] =a[j];
j--;
}
a[j+1]=key;
}
}
void insert_recur(int a[],int x){
if(x<=1) return;
insert_recur(a , x-1);
int key = a[x-1];
int j=x-2;
while (j>=0 && a[j]>key)
{
a[j+1]=a[j];
j--;
}
a[j+1]= key;
}
int main()
{
int n;
cout << "Enter no.of elements: ";
cin >> n;
int arr[n];
cout << "Enter the array elements\n";
for (int i = 0; i < n; i++)
{
cin >> arr[i];
}
insert_recur(arr,n);
cout << "Array after sorting:\n";
for (int i = 0; i < n; i++)
{
cout << arr[i] << " ";
}
cout << endl;
return 0;
}