Wednesday 12 October 2011

INSERTION SORT USING TEMPLATES


INSERTION SORT USING TEMPLATES
Aim:
            To write a program to implement insertion sort using templates.

ALGORITHM:

Step 1: Start the process.
Step 2: Get the number of elements to be inserted
Step 3: Store the elements in an array
Step 4: Fix the index position to the first element.
Step 5: Write a routine for comparing the least element in the array
Step 6: Compare the first element with the next element. If the second element is lesser than the first element, then the first element will be swapped. Likewise, all the elements will be compared in many passes.
Step 7: Once the element have be sorted then the sorting routine will get stop.
Step 8: Stop the process.

PROGRAM:

#include<iostream.h>
#include<iomanip.h>
#include<conio.h>
template <class t>
class insertion
{
t a[25];
public:
void get(int);
void sort(int);
void display(int);
};
template <class t>
void insertion<t>::get(int n)
{
int i;
cout<<"\nEnter the array elements:";
for(i=0; i<n;i++)
cin>>a[i];
}
template <class t>
void insertion <t>::display(int n)
{
int i;
cout<<"\nThe sorted array is: \t";
for(i=0;i<n;i++)
cout<<a[i]<<setw(10);
}
template <class t>
void insertion <t>::sort(int n)
{
int i,j;
t temp;
for(i=1;i<n;i++)
{
j=i;
while(j>=1)
{
if(a[j]<a[j-1])
{
temp=a[j];
a[j]=a[j-1];
a[j-1]=temp;
}
j--;
}
}
}
void main()
{
int n,m;
insertion<int> i1;
insertion<float> i2;
clrscr();
cout<<"\nInsertion Sort on Integer Values\n";
cout<<"\nEnter the size of array:\t";
cin>>n;
i1.get(n);
i1.sort(n);
i1.display(n);
cout<<"\n\nInsertion Sort on Float Values\n";
cout<<"\nEnter the size of array:\t";
cin>>m;
i2.get(m);
i2.sort(m);
i2.display(m);
getch();
}

OUTPUT:
Insertion Sort on Integer Values
Enter the size of array:        5
Enter the array elements:23
67
12
78
34

The sorted array is:    12        23        34        67        78

Insertion Sort on Float Values
Enter the size of array:        3
Enter the array elements:13.3
29.0
12.7

The sorted array is:    12.7      13.3        29

RESULT:
Thus the program to implement insertion sort using templates was executed.

0 comments:

Post a Comment