Bitpath

Searching & Sorting

Find things in sorted data in a handful of steps, then learn how data gets sorted in the first place: the simple quadratic sorts, merge sort and quicksort, and how to use the sort your language already ships.

  • Beginner
  • 4 units, 12 lessons, 148 exercises
  • Python, JavaScript or TypeScript
  • Builds on Algorithm Foundations, a little of Recursion & Backtracking

Unit 02 · 3 lessons

Simple sorts

Understand sorting by doing it the slow way first

  1. 01Swap your way up
  2. 02Insertion sort
  3. BOSSStable or not
Unit prize
  1. 01
    Swap your way up

    Bubble sort and selection sort, one pass at a time

  2. 02
    Insertion sort

    Slide each item into place; nearly sorted input is nearly free

  3. BOSS
    Stable or not

    Keep ties in order, then sort by two keys

Read the unit guide

Three sorts fit in ten lines each, and all three are O(n²): two nested loops over the list. They are too slow for a million items, but each one teaches an idea that the fast sorts reuse.

Bubble sort compares neighbours and swaps the pairs that are out of order. One pass carries the largest value to the end, so each pass can stop one position earlier. Selection sort scans the unsorted part for its smallest value and swaps it to the front. It always makes about n²/2 comparisons, but at most n - 1 swaps.

Insertion sort is the one worth remembering. It keeps the left part sorted and slides each new item left until it fits, shifting larger items one place right. On input that is already nearly sorted the inner loop barely runs, so the whole sort is close to O(n). Real libraries switch to insertion sort for small or nearly sorted pieces.

A sort is stable when items with equal keys keep their original order. Bubble and insertion sort are stable, as long as they use a strict comparison (>, never >=). Selection sort is not: its long-distance swap can throw an item past an equal one.

Stability is what makes multi-key sorting easy: sort by the secondary key first, then by the primary key with a stable sort. The second sort keeps the first sort's order among ties.

Classic pitfalls: >= where > was meant (stability gone), a loop that stops at index 1 and never compares against index 0, and forgetting that all three are O(n²) in the worst case.

Unit 03 · 3 lessons

Fast sorts

Sort in O(n log n) by splitting the problem in two

  1. 01Merge two sorted lists
  2. 02Merge sort
  3. BOSSQuicksort
Unit prize
  1. 01
    Merge two sorted lists

    Two pointers, one pass, and do not forget the leftovers

  2. 02
    Merge sort

    Split, sort each half, merge: O(n log n) on every input

  3. BOSS
    Quicksort

    Partition around a pivot, then sort each side in place

Read the unit guide

The simple sorts fix one item per pass: n passes of up to n steps. The fast sorts split the list in two, sort each part, and need only about log₂ n levels of splitting. Each level touches every item once, so the total is O(n log n): about 20 million steps for a million items, where an O(n²) sort needs a trillion.

Merge is the building block of merge sort. Given two sorted lists, keep a pointer in each, copy the smaller of the two front items, and advance that pointer. When one list runs out, copy what is left of the other. That is O(n + m), and taking from the left list on ties keeps it stable.

Merge sort splits the list in half, sorts each half by calling itself, and merges the results. A list of 0 or 1 items is the base case. It is O(n log n) on every input and stable, but the merging needs O(n) extra memory.

Quicksort does its work before the recursion. Partition picks a pivot, moves smaller values to its left and the rest to its right, and so puts the pivot in its final position. Then each side is sorted the same way, in place.

Quicksort is only fast when the pivot splits the list roughly in half. With the last item as pivot, an already sorted list gives the worst split every time: O(n²). Real implementations pick a random pivot or the median of three.

Classic pitfalls: forgetting the leftover items after a merge, a base case that misses the 1-item list (the recursion never ends), recursing on a range that still includes the pivot, and believing quicksort is always O(n log n).

Unit 04 · 3 lessons

Sorting in practice

Use the built-in sort well, and binary search for answers

  1. 01The sort you already have
  2. 02Sort by a key
  3. BOSSSearch for the answer
Unit prize
  1. 01
    The sort you already have

    In place or a copy, and the trap in the default order

  2. 02
    Sort by a key

    Key functions, comparators, descending order and tie-breakers

  3. BOSS
    Search for the answer

    Counting sort, then binary search with no list at all

Read the unit guide

In real code you call the sort your language ships. It is O(n log n), stable, and tuned for real data: Python and the V8 engine behind Chrome and Node use Timsort, a merge sort that switches to insertion sort on short runs. Writing your own is for learning.

Know whether a sort works in place or returns a new list. Python's list.sort() and JavaScript's array.sort() change the list itself; sorted(list) and toSorted() leave it alone and return a sorted copy. And know the JavaScript trap: with no comparator, sort() compares items as text, so 100 comes before 9.

A comparator takes two items and returns a negative number if the first goes first, a positive number if the second does, and 0 for a tie. A key function takes one item and returns the value to sort by. Python uses keys; JavaScript and TypeScript use comparators that compare keys.

Ties are broken with a second key: a tuple key in Python, a chained comparison in JavaScript. Or sort twice with a stable sort, least important key first.

Comparison sorts cannot beat O(n log n), but counting sort does not compare: with small whole-number values it tallies each value and writes them out in O(n + range).

Binary search also works on answers. When "is this value good enough?" flips from no to yes exactly once as the value grows, you can binary search for the boundary, even though no list exists. Classic pitfalls: sorting numbers as text, a comparator that returns true or false, and a search range that does not contain the answer.

Learn Searching & Sorting on your phone.

Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.

One email when Bitpath is ready to try. Nothing else. Privacy