SORTING · 8 MIN
Bubble Sort
Repeatedly swap adjacent out-of-order pairs; the largest value bubbles to the end each pass.
BYTE explains
- Pass i pushes the i-th largest element into its final place.
- If a pass makes no swaps, the array is sorted — stop early.
- Time O(n²) worst case, O(n) best case with the early stop, space O(1).
Real world: Students in a line swapping with their neighbour until heights are in order.
Watch it move
Start: unsorted array
1/47
Code
def bubble(a):
for i in range(len(a)):
swapped = False
for j in range(len(a) - 1 - i):
if a[j] > a[j+1]:
a[j], a[j+1] = a[j+1], a[j]
swapped = True
if not swapped: break
return aTry it in the online compiler →Checkpoint quiz
Best-case time of bubble sort with early stop?