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.
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.
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.
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.
After the third pass, the resultant array is as shown below.
After the fourth pass, the resultant array is as shown below.
After the fifth pass, the resultant array is as shown below.
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.