Bubble Sort Working Mechanism

For Complete YouTube Video: Click Here

In this class, we will try to understand Bubble Sort Working Mechanism.

We have discussed the working mechanism of selection sort and algorithm of selection sort in our previous classes.

Bubble Sort Working Mechanism

The name bubble represents the way a bubble rises in the water.

In the same way, the largest element will be moved to the end of the array.

For better understanding, we will consider the array of elements shown below.

Bubble Sort Working Mechanism 1
Bubble Sort Working Mechanism 1

In each iteration, we will compare two elements.

If A[i] > A[i+1] the elements will be swapped.

From the above array, first, we will compare A[0] > A[1].

4 > 8 is false swapping NOT done.

Next, 8 > 3 is compared.

8 > 3 is true swapping is done as shown below.

Bubble Sort Working Mechanism 2
Bubble Sort Working Mechanism 2

8 > 1 is compared.

8 > 1 is true swapping is done as shown below.

Similarly, all the elements are compared and the resultant array after the first pass [iteration] is as shown below.

Bubble Sort Working Mechanism 7
Bubble Sort Working Mechanism 7

On the elements after first pass the second round of comparisions is done as explained above.

The final resultant array after the second round is as shown below.

Bubble Sort Working Mechanism 8
Bubble Sort Working Mechanism 8

After the third pass, the resultant array is as shown below.

Bubble Sort Working Mechanism 9
Bubble Sort Working Mechanism 9

After the fourth pass, the resultant array is as shown below.

Bubble Sort Working Mechanism 10
Bubble Sort Working 10

After the fifth pass, the resultant array is as shown below.

Bubble Sort Working Mechanism 11
Bubble Sort Working 11

An essential point to understand is after the fifth pass, all the elements are in sorted order.

Even though the elements are sorted, all eight comparisons are made.

The is the main drawback of the bubble sort.

We have an optimized version of the bubble sort algorithm to overcome this drawback.

In the following two classes, we will cover the bubble sort’s original and optimized version.