Compare neighbours and swap them when they are out of order. After each pass the biggest unsorted value has bubbled to the end.
Python · intermediate · 7 min · 38 steps · free
def bubble_sort(items):
n = len(items)
for end in range(n - 1, 0, -1):
swapped = False
for i in range(end):
if items[i] > items[i + 1]:
items[i], items[i + 1] = items[i + 1], items[i]
swapped = True
if not swapped:
break
return items
print(bubble_sort([5, 1, 4, 2]))bubble_sort(). Its body does not run yet: it runs each time the function is called.bubble_sort(), with items = [5, 1, 4, 2]. It gets its own names.n is created with the value 4.end is created with the value 3.swapped is created with the value false.i is created with the value 0.items[i] > items[i + 1] is true, so the block under it runs.swapped changes from false to true.i changes from 0 to 1.items[i] > items[i + 1] is true, so the block under it runs.items points to, index 1 changes from 5 to 4 and index 2 changes from 4 to 5.swapped = True.i changes from 1 to 2.items[i] > items[i + 1] is true, so the block under it runs.swapped = True.for i in range(end).not swapped is false, so the block under it is skipped.swapped changes from true to false.i changes from 2 to 0.items[i] > items[i + 1] is false, so the block under it is skipped.i changes from 0 to 1.items[i] > items[i + 1] is true, so the block under it runs.items points to, index 1 changes from 4 to 2 and index 2 changes from 2 to 4.swapped changes from false to true.for i in range(end).not swapped is false, so the block under it is skipped.end changes from 2 to 1.swapped changes from true to false.i changes from 1 to 0.items[i] > items[i + 1] is false, so the block under it is skipped.for i in range(end).break.items.bubble_sort() has finished, so its names are gone. It prints [1, 2, 4, 5].Answer: 1
Answer: O(n²)
← Sliding Window · Selection Sort →