Bubble Sort

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

What you'll learn

bubble_sort.py

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]))

Step by step

  1. Python defines the function bubble_sort(). Its body does not run yet: it runs each time the function is called.
  2. Python calls bubble_sort(), with items = [5, 1, 4, 2]. It gets its own names.
  3. n is created with the value 4.
  4. end is created with the value 3.
  5. swapped is created with the value false.
  6. i is created with the value 0.
  7. items[i] > items[i + 1] is true, so the block under it runs.
  8. 5 > 1, so they swap places in one line: Python swaps both at once.
  9. swapped changes from false to true.
  10. i changes from 0 to 1.
  11. items[i] > items[i + 1] is true, so the block under it runs.
  12. In the list that items points to, index 1 changes from 5 to 4 and index 2 changes from 4 to 5.
  13. Line runs: swapped = True.
  14. i changes from 1 to 2.
  15. items[i] > items[i + 1] is true, so the block under it runs.
  16. 5 keeps moving right and reaches the end. After one pass, the largest value is in its final place.
  17. Line runs: swapped = True.
  18. Python moves to the next item of the loop: for i in range(end).
  19. not swapped is false, so the block under it is skipped.
  20. The next pass can stop one place earlier: the last spot is done.
  21. swapped changes from true to false.
  22. i changes from 2 to 0.
  23. items[i] > items[i + 1] is false, so the block under it is skipped.
  24. i changes from 0 to 1.
  25. items[i] > items[i + 1] is true, so the block under it runs.
  26. In the list that items points to, index 1 changes from 4 to 2 and index 2 changes from 2 to 4.
  27. swapped changes from false to true.
  28. Python moves to the next item of the loop: for i in range(end).
  29. not swapped is false, so the block under it is skipped.
  30. end changes from 2 to 1.
  31. swapped changes from true to false.
  32. i changes from 1 to 0.
  33. items[i] > items[i + 1] is false, so the block under it is skipped.
  34. Python moves to the next item of the loop: for i in range(end).
  35. No swaps in this pass, so the list is sorted: stop early.
  36. Line runs: break.
  37. The function returns items.
  38. bubble_sort() has finished, so its names are gone. It prints [1, 2, 4, 5].

Common mistakes

Best practices

Key takeaways

Check yourself

Bubble sort on [1, 2, 3] with the swapped check: passes?

Answer: 1

Worst-case cost?

Answer: O(n²)

·

More in Sorting