Bubble Sort Program in C Plus Plus
Bubble sort is an efficient sorting technique in the
data structure using which you can efficiently sort the data in ascending or
descending order.
In this article we will develop a C ++ program of
bubble sort which will take the data from the user and sort it to the ascending
order.
You can also sort the data in the descending order using
bubble sort by making the minor changes in the program code.
How this Program Works
All we have done is that we have simply transform the
algorithm of Bubble sort in the in C++
programming language.
The algorithm of bubble sort is as under.
Algorithm of Bubble Sort
Bubble (DATA, N)
Here DATA is an array with N elements. This algorithm
sorts the elements in DATA.
1.
Repeat Steps 2 and 3 for K=1 to N-1.
2.
Set PTR:=1. [Initializes pass pointer
PTR.]
3.
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.
How this Program Behave
This program will ask the user to enter the numbers to
be sorted. User will enter the numbers program will sort these numbers.
Program of Binary Search
//softoset.blogspot.com
//Bubble Sort
#include<iostream>
using namespace std;
#define MAX 100
int main()
{
int
Data[MAX],size;
cout<<"How
many Element You Want to insert "<<endl;
cin>>size;
cout<<"Enter
Elements "<<endl;
for(int
i=1;i<=size;i++)
{cout<<"["<<i<<"]"<<"
= ";cin>>Data[i];
}
for(int
j=1;j<size-1;j++)
{
int
ptr=1;
while(ptr<=size-j)
{
if(Data[ptr]>Data[ptr+1])
{
int
temp=Data[ptr];
Data[ptr]=Data[ptr+1];
Data[ptr+1]=temp;
}
ptr++;
}
}
cout<<"Sorted
Eements"<<endl;
for(int
i=1;i<size+1;i++)
{cout<<"["<<i<<"]"<<"
= "<<Data[i]<<endl;;
}
return
0;
}
Output of
Program Binary Search
This is the sample output from the program on the
first run.
You can clearly see that this program has successfully
sort the data in ascending order.
SoftOSet.
Reset Your Technology.
Post a Comment
Feel Free to Comment Us