C++ Program Code is for implementing the insertion sort algorithm on an array, utilizing template class concept

Leave a Comment
/* The following C++ Program Code is for implementing the insertion sort algorithm on an array. To attain the compatibility for various data types, template class concept is used. The user is asked about the number of element he want to put in the array. Then he also enters the elements & the insertion sort algorithm is applied, & thus result is displayed */

#include<iostream>
#include<stdlib.h>
using namespace std;

template<class T>
void isort(T a[],int n)
{
     int i;
     for(i=1;i<n;i++)
     {
             T t=a[i];
             int j;
             for(j=i-1;j>=0&&t<a[j];j--)
             {
                                           a[j+1]=a[j];
             }
             a[j+1]=t;
     }
}


void main()
{
    int a[100],i,n;
    cout<<"Enter number of elements : ";
    cin>>n;
    cout<<"Enter elements (Use Spacebar as Separator)\n";
    for(i=0;i<n;i++)
    {
                    cin>>a[i];
    }
    isort(a,n);
    cout<<"After sorting the elements are\n";
    for(i=0;i<n;i++)
    {
                    cout<<a[i]<<"\n";
    }
    system("pause");
}


Screenshot:
C++ Program Code is for implementing the insertion sort algorithm on an array, utilizing template class concept

0 comments: