Bubble Sort Algorithm
For Complete YouTube Video: Click Here
In this class, we will try to understand Bubble Sort Algorithm.
We have discussed the working mechanism of bubble sort in our previous class.
Bubble Sort Algorithm
The image below shows the Bubble Sort Algorithm.
We will consider the following array to understand the algorithm better.
In the above algorithm, the outer for loop (i) runs from 0 to n-1 from 0 to 7.
In every iteration, the inner for loop (j) will iterate from 0 to n – i – 1.
Why n – i -1 is used very important to understand.
When the value of i = 0 the inner for loop will iterate from j = 0 to 7.
Similarly, when the i = 1 the j will iterate from j = 0 to 6.
n – i – 1 is used because once all the iterations of the inner for loop are made, the largest element in the array will be moved to the end.
In this way, the elements will get arranged in sorted order.
But the algorithm’s demerit is that after the elements are in sorted order, the algorithm will do all the iterations.
In our next class, we will discuss the optimized solution for the bubble sort.