Wednesday, March 25, 2015

Insertion Sort

Here is the code for Insertion Sort.
#include <iostream>

using namespace std;

void ins_sort(int a[],int n)
{
    for(int i = 1; i < n; i++)
    {
        int key = a[i];
        int j = i-1;
        while(j>=0 && a[j]>key)
        {
            a[j+1] = a[j];
            j--;
        }
        a[j+1] = key;
    }
}

int main()
{
    int n;
    cin>>n;
    int a[n];
    for(int i = 0; i < n; i++)
        cin>>a[i];
    ins_sort(a,n);
    for(int i = 0; i < n; i++)
        cout<<a[i]<<" ";
    cout<<endl;
    return 0;
}

If you have any doubts, kindly leave them in the comments :)
Best of luck !!

Monday, March 23, 2015