Sunday 6 October 2013

Insertion Sort program in C++

//insertion sort
#include<iostream>
using namespace std;
#include<conio.h>
template<class T>
void insertionsort(T a[],int n)
{
     for(int i=1;i<n;i++)
     {
             T temp=a[i];
             int j;
             for(j=i-1;j>=0&&temp<a[j];j--)
             {
                                           a[j+1]=a[j];
             }
             a[j+1]=temp;
     }
}
int main()
{
    int a[50],i,n;
    cout<<"enter number of elements do u want to sort :";
    cin>>n;
    cout<<"enter elements to sort:";
    for(i=0;i<n;i++)
    {
                    cin>>a[i];
    }
    insertionsort(a,n);
    cout<<"after sorting the elements are....";
    for(i=0;i<n;i++)
    {
                    cout<<a[i]<<"\n";
    }
    _getch();
    return 0;
}

No comments:

Post a Comment