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
#include <bits/stdc++.h>
using namespace std;
void print(int a[], int n)
{
for (int i = 0; i < n; i++)
{
cout << a[i] << " ";
}
cout << endl;
}
// InsertSort
void insertSort(int a[], int n)
{
for (int i = 0; i < n; i++)
{
int hole = i;
int val = a[i];
while (hole > 0 && a[hole - 1] > val)
{
a[hole] = a[hole - 1];
hole = hole - 1;
}
a[hole] = val;
}
print(a, n);
}
signed main(){
int n;
cin >> n;
int a[n];
for (int i = 0; i < n; i++)
{
cin >> a[i];
}
InsertSort(a, n);
print(a, n);
return 0;
}
Insertion sort is a simple sorting algorithm that works similar to the way you sort playing cards in your hands. The array is virtually split into a sorted and an unsorted part. Values from the unsorted part are picked and placed at the correct position in the sorted part.