Sorting & Searching, Explained
You already call .sort() and in without thinking twice. That's fine for most code - but the moment
something is slow, or an interviewer asks "how would you find this faster," you need the picture underneath
the built-in. Two questions drive almost everything here: how do I find a value fast? and how do I put
things in order in the first place? Each answer builds on the one before it - sorting exists partly to make
searching faster.
This guide keeps the code in Python so you can run every example as you read.
How to read this
Read in order - binary search only makes sense once you've felt why linear search is slow, and every sort after bubble sort is really "here's a cleverer way to avoid bubble sort's problem."
The phases
- Linear vs. Binary Search - the two ways to find a value, and why sorted order unlocks a dramatically faster search.
- Binary Search, Implemented - the real algorithm on a sorted array, its complexity, and the off-by-one bugs that catch almost everyone once.
- Bubble Sort - the simplest sort there is: compare neighbors, swap, repeat. Slow, but it builds the intuition every other sort refines.
- Merge Sort (and Quick Sort) - divide and conquer: split the problem in half, solve the halves, combine. The shape behind every fast general-purpose sort.