C++ program to sort an array of elements using Bubble Sort
Aim:
To write a program to an array of elements using bubble sort technique.
Algorithm:
BUBBLE ( DATA, N)
Here DATA is an array with N elements. This algorithm sorts the elements in DATA.
- Repeat Steps 2 and 3 for K=1 to N-1.
-
Set PTR : =1. [Initializes pass pointer PTR.]
-
Repeat while PTR<= N – K : [Executes pass.]
(a) If DATA [PTR] > DATA [PTR + 1], then:
Interchange DATA [PTR] and DATA [PTR + 1].
[End of If structure.]
(b) Set PTR : = PTR + 1.
[End of inner loop]
[End of Step 1 outer loop.]
4. Exit.
Program code:
#include<iostream.h>
#include<conio.h>
class bubble
{
int a[20],l,i;
public:
void read()
{
cout<<"Enter the array length : ";
cin>>l;
cout<<"Enter the elements : ";
for(i=1;i<=l;i++)
{
cin>>a[i];
}
}
void sort()
{
int k,j,t;
for(k=1;k<=L-1;k++)
{
for(j=1;j<=l-1;j++)
{
if(a[j]>a[j+1])
{
t=a[j];
a[j]=a[j+1];
a[j+1]=t;
}
}
}
}
void display()
{
cout<<"\nSorted array is \n":
for(i=1;i<=l;i++)
{
cout<<a[i]<<" ";
}
}
};
void main()
{
clrscr();
bubble b;
b.read();
b.sort();
b.display();
getch();
}
Output:
Enter the array length : 6
Enter the elements : 1 8 3 7 2 6
Sorted array is
1 2 3 6 7 8