Bubble sort
Bubble sort
Bubble Sort
Pre-Requisites
Function
Loop
Arrays
How to optimize the bubble sort in the case of nearly sorted arrays
As we are now familiar with the concept of Recursion from the previous lesson, we will now expand our
This algorithm works on the principle of swapping adjacent elements if they are not in sorted order and it keeps
swapping until the final array becomes sorted. At each pass we keep on checking the adjacent elements and
reach the end of the array, this will make the last element of the array sorted and keep repeating this process
Example:
In the above example, we keep comparing the adjacent elements and perform the required operations as
follows:
First Pass: Check 1 is between 10 and 40, so no need to swap here. The 2nd check is between 40 and 30 so here,
The 3rd check is between 40 and 50, they are in correct order so no need to swap them, and the 4th check is
between 50 and 20, and we know that 50 > 20, so we need to swap them.
First Pass
Second Pass
Third Pass: Now we know that the last 2 elements of the array will be at their correct positions in sorted order as
2 passes are already done, so we do not need to check them.
First check will be of 10 and 30, they are already in sorted order so no need to swap them, 2nd check will be of
30 and 20 and we know that 30 > 20, so we need to swap them.
Third Pass
Fourth Pass:
Before starting the fourth pass, the last 3 elements will be at their correct positions as 3 passes are already
done, So we do not need to check them. So the first check is 10 and 20, they are already at the correct position
so no need to swap them. No need to check further as they are already sorted .
Fourth Pass
https://pastebin.com/UgtZa2hC
Output
Maximum number of swaps in 2nd pass will be (n-2) as last element will already be maximum after 1st pass.
Maximum number of swaps in 3rd pass will be (n-3) as last 2 elements will already be sorted after 2nd pass.
Similarly in the last pass or (n-1)th pass, the maximum number of swaps can be 1.
Note: The maximum number of swaps occurs when the array is strictly decreasing in nature.
If you find there is no swapping in a particular pass, it means the array has become sorted, so you should not
go for the further passes. For this you can use a flag variable which is set to true before each pass and is made
to false whenever a swapping operation is executed.
Code Link
https://pastebin.com/0r8yUC5K
Note- that if all the passes are performed, then our optimized algorithm will in fact perform a little slower than
the original one.
For example, Take a look at the picture below. The unsorted array has two elements with value 30. Note the
order of both these elements in the stable and unstable sorted arrays.
Yes, Bubble Sort is a stable sorting algorithm. We swap elements only when A is less than B. If A is equal to B, we
do not swap them, hence relative order between equal elements will be maintained.