Wednesday 12 October 2011

IMPLEMENTATION OF BUBBLE SORT


IMPLEMENTATION OF BUBBLE SORT

AIM:
             To write a program to implement bubble sort using templates
 ALGORITHM:

Step 1:Start the process.
Step 2:Get the number of elements to be sorted.
Step 3:Get the elements from the user.
Step 4:For iteration=1 to n,
            a. Assign the first element to the variable “i” and the second element to the variable “j”.
            b.Compare the two elements.
            c.If the first element is greater than the second element then swap the two values. Else break.
Step 5:Continue the steps 4 until there is no interchange in the current iteration.
Step 6;No interchange indicates the elements are sorted.
Step 7: Stop the process.

PROGRAM:

#include<iostream.h>
#include<iomanip.h>
#include<conio.h>
template <class t>
class bubble
{
t a[25];
public:
void get(int);
void sort(int);
void display(int);
};
template <class t>
void bubble <t>::get(int n)
{
int i;
cout<<"\nEnter the array elements:";
for(i=0; i<n;i++)
cin>>a[i];
}
template <class t>
void bubble <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 bubble <t>::sort(int n)
{
int i,j;
t temp;
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
}
void main()
{
int n,m;
bubble<int> b1;
bubble<float> b2;
clrscr();
cout<<"\n----Bubble Sort on Integer Values----";
cout<<"\nEnter the size of array:\n";
cin>>n;
b1.get(n);
b1.sort(n);
b1.display(n);
cout<<"\n\n----Bubble Sort on Float values----\n";
cout<<"\nEnter the size of array:\n";
cin>>m;
b2.get(m);
b2.sort(m);
b2.display(m);
getch();
}

OUTPUT:

----Bubble Sort on Integer Values----
Enter the size of array: 5

Enter the array elements: 3 6 1 2 9

The sorted array is:    1         2         3         6         9

----Bubble Sort on Float values----

Enter the size of array: 5

Enter the array elements: 1.2 5.7 3.6 2.0 4.6

The sorted array is:    1.2         2       3.6       4.6       5.7

RESULT:
Thus the program to implement Bubble Sort using templates was executed.

0 comments:

Post a Comment