Skip to main content

Insertion sort

//Insert an element from unsorted array to its corect position
// in sorted array by checking that element with each elements
// of the sorted array using a for loop.

#include <iostream>
#include <vector>
#include <algorithm>
#include <bits/stdc++.h>
using namespace std;

int main()
{

int n;
cin >> n;

vector<int> v(n);

for (int i = 0; i < n; i++)
{
cin >> v.at(i);
}

//Insertion Sort Algorithm
for (int i = 1; i < n; i++)
{
int j = i - 1;
int current = v.at(i); //v[i] can also be used
while (j >= 0 && v.at(j) > current)
{
j = j - 1;
}
v.at(j + 1) = current;
}

for (auto el : v)
cout << el << " ";

cout << endl;

//<==<==<==<==<==<==STL std::sort()⏩⏩⏩⏩⏩⏩
//also refer ⏩ http://www.cplusplus.com/reference/algorithm/sort/
//also refer ⏩ https://www.geeksforgeeks.org/sort-c-stl/

// sort(v.begin(), v.begin() + n);
// for (auto el : v)
// cout << el << " ";

return 0;
}