Bubble sort is a reasonably elegant sorting algorithm that has a lot in common with the in-place version of insertion sort. Bubble sort is by definition an in-place algorithm. It cycles through the list, from front to back, swapping neighboring items if they are not in the correct order. It continues cycling through the list until no more swaps are made. This algorithm is short and elegant:
def bubble_sort( tlist ):
while True:
swap = False
for i in range( len( tlist )-1 ):
if tlist[i] > tlist[i+1]:
tlist[i], tlist[i+1] = tlist[i+1], tlist[i]
swap = True
if not swap:
return
numlist = [8, 3, 5, 11, 5, 33, 2, 2, 0, 9, 12, 26, 1, 9, 18]
bubble_sort( numlist )
print( numlist )
Exercise: Determine big-O and big-Omega for bubble sort.
Answer: Each cycle through the list, the item that is at the end of the original list can only be moved one position to the front. So if the item that is at the end of the original list is actually the item that should end up at index 0, the list is cycled through n
times. Since each cycle touches each item once, the algorithm is O(n
²)
. The best-case scenario is that the list is sorted to begin with. In that case, no swaps are made at all, and the list is only processed once. So the algorithm is Ω(n)
.
The time complexity of bubble sort is the same as of insertion sort. Its implementation is too. A close analysis will show that insertion sort tends to have a slight computational advantage. For instance, if you have a list that is already completely sorted, except that the very last item of the list should actually be at the front, then insertion sort needs about n
checks and n
swaps, while bubble sort needs about n
² checks and n
swaps. However, bubble sort has a slight advantage in being a bit easier to understand and implement (though I guess that is subjective).