Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order.
Following are the steps involved in bubble sort (for sorting a given array in ascending order):
o 🔴 Starting with the first element (index = 0), compare the current element with the next element of the array.
o 🔴If the current element is greater than the next element of the array, swap them.
o 🔴If the current element is less than the next element, move to the next element. Repeat Step 1.
Bubble Sort Code Example In C++
#include<iostream>
#include<conio.h>
using namespace::std;
class ali{
private:
int array[5];
public:
insertdata(){
for(int i=0;i<5;i++)
{
cin>>array[i];
}
}
display(){
cout<<endl<<"your entered data is : "<<endl;
for(int i=0;i<5;i++)
cout<<endl<<array[i]<<endl;
}
sorting(){
for(int e=0;e<4;e++){
for(int r=e+1;r<5;r++){
if(array[e]>array[r])
{
int z;
z=array[e];
array[e]=array[r];
array[r]=z;
}
}
}
}
};
int main()
{
ali* er=new ali;
er->insertdata();
er->display();
er->sorting();
cout<<endl<<"after sorting :"<<endl;
er->display();
getch();
}
No comments:
Post a Comment