Saturday 17 September 2011

Bubble sort using class template


Bubble sort using class template
Aim:
To write a C++ program for bubble sort using template.
 Algorithm:
Step 1: Specify the template declaration and create a class as bubble.
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 bub
{
T *v;
int s;
public:
bub(int x)
{
s=x;
v=new T[s];
}
void read();
void sort();
void display();
~bub()
{
delete v;
}
};

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

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

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

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

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

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

bub<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

3 comments:

Unknown said...



Very informative article.Thank you author for posting this kind of article .


http://www.wikitechy.com/view-article/bubble-sort-program-in-cpp-with-example



Both are really good,
Cheers,
Venkat

Tom said...

Can anyone please post the output of this program

Tom said...

Can anyone please post the output of this program

Post a Comment