Skip to content

Sorting Visualized

Sorting is one of the first “real” algorithms every programmer meets. The idea is simple — put items in order — but how you get there is where the interesting differences live. This page starts with the most intuitive one, bubble sort, and lets you watch it run.

What you’ll learn

  • how bubble sort compares neighbours and swaps them
  • why the biggest values “bubble” to the end each pass
  • how to write it yourself, and when to just call sorted()sorted()

How bubble sort works

Bubble sort walks the list, compares each adjacent pair, and swaps them if they’re out of order. After one full pass the largest value has moved to the end. Repeat, and the list sorts itself from the back forward.

bubble_sort.py
def bubble_sort(nums):
    n = len(nums)
    for i in range(n):
        # after i passes, the last i items are already in place
        for j in range(0, n - 1 - i):
            if nums[j] > nums[j + 1]:
                # swap the out-of-order pair
                nums[j], nums[j + 1] = nums[j + 1], nums[j]
    return nums
 
print(bubble_sort([5, 2, 9, 1, 6]))   # [1, 2, 5, 6, 9]
bubble_sort.py
def bubble_sort(nums):
    n = len(nums)
    for i in range(n):
        # after i passes, the last i items are already in place
        for j in range(0, n - 1 - i):
            if nums[j] > nums[j + 1]:
                # swap the out-of-order pair
                nums[j], nums[j + 1] = nums[j + 1], nums[j]
    return nums
 
print(bubble_sort([5, 2, 9, 1, 6]))   # [1, 2, 5, 6, 9]

Watch it run

Yellow bars are the pair being compared; green bars at the right are locked in their final place. Click the canvas to shuffle and run again.

sketch Bubble sort in motion p5.js
Adjacent bars are compared and swapped so the largest values bubble to the end. Click to reshuffle.

Bubble sort is easy to understand but slow: for a list of n items it does about comparisons. For real work you’ll reach for Python’s built-in sorted()sorted() (a highly optimized Timsort) — but knowing how a sort works under the hood is what this page is for.

Try it: Sorting Exercises

Exercise 1 – Swap two values

Exercise 2 – One bubble-sort pass

Exercise 3 – Use sorted()

If this helped you, consider buying me a coffee ☕

Buy me a coffee

Was this page helpful?

Let us know how we did