Bubble sort (Sinking sort)
We repeatedly compare adjacent values and swap if is in an incorrect order.
So, here you can see some values which needs to be sorted. First we will compare 1st 2 values ,
Here 5<9 thus we will not swap. Let's move to the next pair then.
This process will go untill the last element.
So, after complete iteration the biggest value will move to the right
Let's start the 2nd iteration:
After the 2nd iteration 8 & 9 will be sorted
After 3rd iteration we will have:
This process will continue and finally we will have:
All sorted in the ascending order.
Code for Bubble sort:
def bubbleSort(customList):
for i in range(len(customList)-1):
for j in range(len(customList)-i-1):
if customList[j] > customList[j+1]:
customList[j], customList[j+1] = customList[j+1], customList[j]
print(customList)
Complexity Analysis
When to use Bubble Sort?
- When the input is already sorted.
- Space is a concern.
- Easy to implement.
When to avoid Bubble Sort?
Average time complexity is poor.
Top comments (0)