Computer Scientists are Pretty Pessimistic

Wednesday, 11 May 2016

Insertion Sort

Algorithm : :
x0 ← -∞
for j=2 to n do
     i ← j-1
     t ← xj
while t < xi do
           xi+1 ← xi
           i ← i-1
     xi+1 ← t


CODE : :

#include <iostream>
using namespace std;
int main ()
{
    int array[100],n;
    cout<<"Enter Number of Elements:"<<endl;
    cin>>n;
    cout<<"Enter Elements:"<<endl;
    for(int i=1;i<=n;i++)
        cin>>array[i];
    array[0]=INT_MIN;
    for(int j=2;j<=n;j++)
    {
        int i=j-1;
        int t = array[j];
        while(t<array[i])
        {
            array[i+1]=array[i];
            i--;
        }
        array[i+1]=t;
    }
    for(int i=1;i<=n;i++)
        cout<<array[i]<<" ";
    return 0;
}

No comments:

Post a Comment