Insertion Sort

- 1 min

This algorithm is based on sorting cards in your hand. This is one of the first basic algorithms that is taught.

#include <iostream>
#include <vector>

using namespace std;

void swap(int &a, int &b) 
{
        int temp = a;
        a = b;
        b = temp;
}

void insertionsort(vector<int>& a)
{
    for(auto i=1;i<a.size(); ++i)
    {
        for(auto j=i; j>0; --j)
        {
            if(a[j]<a[j-1])
            {
                swap(a[j],a[j-1]);
            }
        }
    }
}

int main()
{
    vector<int> a{12, 8, 3, 7, 10, 8, 23, 5, 17};
    insertionsort(a);
    for(auto x:a)
        cout<<x<<" ";
    return 0;
}

Time Complexity:

Worst Case Average Case Best Case
O(n2) O(n2) O(n)

Space Complexity:

O(1)

Vidhatha Vivekananda

Vidhatha Vivekananda

Programmer. Interested in nature and philosophy.

rss facebook twitter github gitlab youtube mail spotify lastfm instagram linkedin google google-plus pinterest medium vimeo stackoverflow reddit quora quora