Bubble sort is one of the simplest sorting algorithms. The two adjacent elements of a list are checked and swapped if they are in wrong order and this process is repeated until we get a sorted list. The steps of performing a bubble sort are:
- Compare the first and the second element of the list and swap them if they are in wrong order.
- Compare the second and the third element of the list and swap them if they are in wrong order.
- Proceed till the last element of the list in a similar fashion.
- Repeat all of the above steps until the list is sorted.
This will be more clear by the following visualizations.
Initial list
First iteration
SWAP
SWAP
Second iteration
SWAP
SWAP
Third iteration
No swap → Sorted → break the loop
Let’s code this up.
a = [16, 19, 11, 15, 10, 12, 14]
#repeating loop len(a)(number of elements) number of times
for j in range(len(a)):
#initially swapped is false
swapped = False
i = 0
while i<len(a)-1:
#comparing the adjacent elements
if a[i]>a[i+1]:
#swapping
a[i],a[i+1] = a[i+1],a[i]
#Changing the value of swapped
swapped = True
i = i+1
#if swapped is false then the list is sorted
#we can stop the loop
if swapped == False:
break
print (a)
In this code, we are just comparing the adjacents elements and swapping them if they are not in order. We are repeating this process len(a) number of times (number of elements in the list). We have also assigned a variable ‘swapped’ and making it ‘True’ if any two elements get swapped in an iteration. If no interchanging of elements happens then the list is already sorted and thus no change in the value of the ‘swapped’ happens and we can break the loop.