Saturday 17 September 2011

Insertion sort using class template


Insertion sort using class template
Aim:
To write a C++ program for insertion sort using template.
 Algorithm:
Step 1: Specify the template declaration and create a class as insertion.
Step 2: Declare the data members as size and *v as template variable.
Step 3: Allocate the memory space using default constructor.
Step 4: Destroy the memory space using destructor.
Step 5: Declare the member functions as
void read()
void sort()
void display()
Step 6: read() function is used to get the elements.
Step 7: sort() function is used to sort the elements.
7.1 Use the for loop to continue the iteration.
7.2 if statement is used to compare the element, if it is true, swap the elements.
Step 8: display() function is used to display the element.
Step 9: In the main, create the object using the following syntax:
  classname<datatype>object
Step10: Call the read() function, to get the elements.
Step11: Call the sort() function, to sort the elements.
Step12: Call the display() function, to display the sorted elements.

Program:

#include<iostream.h>
#include<conio.h>

template<class T>
class insert
{
T *v;
int s;
public:
insert(int x)
{
s=x;
v=new T[s];
}
void read();
void sort();
void display();
~insert()
{
delete v;
}
};

template<class T>
void insert<T>::read()
{
for(int i=0;i<s;i++)
{
cin>>v[i];
}
}

template<class T>
void insert<T>::display()
{
for(int i=0;i<s;i++)
{
cout<<v[i]<<"\t";
}
cout<<"\n";
}

template<class T>
void insert<T>::sort()
{
for(int i=1;i<s;i++)
{
T t=v[i];
for(int j=i-1;j>=0 && t<v[j];j--)
v[j+1]=v[j];
v[j+1]=t;
display();
}
}

void main()
{
clrscr();
int r;
cout<<"\n\nEnter the size:";
cin>>r;

insert<int>I(r);
cout<<"\nEnter the Integer Elements:";
I.read();
I.sort();

insert<float>I1(r);
cout<<"\n\nEnter the Float Elements:";
I1.read();
I1.sort();

insert<char>I2(r);
cout<<"\n\nEnter the Character Elements:";
I2.read();
I2.sort();

getch();
}

Output:

Enter the size:5

Enter the Integer Elements:23   12   11   45   1
12      23      11      45      1
11      12      23      45      1
11      12      23      45      1
1       11      12      23      45

Enter the Float Elements: 2.3   1.2   1.1   4.5   1.0
1.2     2.3     1.1     4.5     1
1.1     1.2     2.3     4.5     1
1.1     1.2     2.3     4.5     1
1       1.1     1.2     2.3     4.5

Enter the Character Elements :r  w  a  t  b
r       w       a       t       b
a       r       w       t       b
a       r       t       w       b
a       b       r       t       w

0 comments:

Post a Comment