All topics / Sorting & Searching, Explained

Sorting & Searching, Explained

How computers find things fast and put things in order: linear vs. binary search, then the classic sorts - bubble, merge, and quick - with the intuition behind each one's speed, not just the code.

Download EPUB
  1. Linear vs. Binary Search Linear search checks every item one by one - simple, works on anything, but gets slower the bigger the data. Binary search exploits sorted order to throw away half the remaining data on every step.
  2. Binary Search, Implemented The real binary search algorithm on a sorted array - the iterative version, its O(log n) complexity, and the off-by-one bugs (wrong midpoint, wrong bound update) that trip up almost everyone the first time.
  3. Bubble Sort: Compare, Swap, Repeat The simplest sort there is: walk the list, swap any two neighbors that are out of order, repeat until nothing swaps. Easy to trust, O(n²), and the foundation the next phase's faster sorts improve on.
  4. Merge Sort (and Quick Sort) Merge sort splits the list in half, recursively sorts each half, then merges the sorted halves back together - O(n log n), guaranteed. Quick sort gets the same speed by partitioning around a pivot instead.