Bubble Sort Program in C++ – [Algorithm with Explanation]

 

1. Bubble Sort Program in C++

In this program, we will enter the numbers randomly and these numbers are stored in the array. After entering the numbers the program will start executing and then after sorting the compiler will print sorted array on the screen.

C++

Output:

bubble sort program in c++

Explanation:

First For Loop: First Iteration-

Assume user gives input of 5 numbers.

for(i=0;0<4;0++) The Condition is TRUE so it will enter in the second for loop.

Second For Loop: First Iteration-

for(j=0;0<5-0-1;0++) The Condition is TRUE so the compiler will enter in the if statement.

if(a[0]>a[1])->if(8>7) It means condition is TRUE so temp=10.Now a[j]=a[j+1]->a[0]=a[1]->a[0]=7. And a[j+1]=temp->a[1]=8. So the array will become 7 8 4 5 9 and j will be incremented by 1.

Second For Loop: Second Iteration-

for(j=1;1<5-0-1;1++) the condition is TRUE so the compiler will enter into if statement if(8>4) it means the condition is TRUE.

So like this process continuously goes on.

Improving Efficiency of Bubble Sort:

It is quite possible that the array gets sorted before all n-1 passes are complete. To avoid unnecessary passes, we have to check whether the array has got sorted at the end of each pass.

This can be done by finding out if an interchange was made in a pass. If no interchanges were done, it implies that the array has got sorted. It can be checked by using a flag.

Bubble Sort Improving Efficiency Algorithm:

1 Step: START.

2 Step: Pass=1.

3 Step: swap=FALSE.

4 Step: i=0.

5 Step: If x[i]>x[i+1] then Interchange x[i] and x[i+1] and Swap=TRUE.

6 Step: i=i+1.

7 Step: If i<=n-Pass-1 then go to step 5.

8 Step: If swap=FALSE then go to step 11.

9 Step: Pass=Pass+1.

10 Step: If Pass<n then go to step 3.

11 Step: STOP.

2. Improved Bubble Sort Program in C++

C++

Output:

bubble sort program in c++

No comments