Sorting Algorithms

Bubble sort explained with a Python example

Bubble sort explained: how neighbouring swaps carry the largest item to the end each pass, when to stop early, why it is O(n²), and a worked Python example.

  • 7 min read
  • 5 questions
  • +35 XP
Transcript

Bubble Sort, explained by cats. Kitty has a line of tuna cans. Big ones. Small ones. All mixed up. Kitty wants them sorted. Smallest to biggest. So she starts at the front. Looks at two cans. If the left can is bigger, swap them.

In this case, it's not. Then move one step forward. Compare again. Swap again if needed. She keeps doing this all the way to the end. After one full pass, the biggest can has bubbled to the top. Then Kitty starts again.

And again. Until no swaps happen. That’s Bubble Sort. Compare two neighbors. Swap if they’re in the wrong order. Repeat until everything is sorted. Simple? Yes. Fast? Not really. Bubble Sort is easy to understand, but terrible for big piles of tuna.