Algorithms from zero
Sorting and search: multiple-choice review
Six questions that cut across the whole unit. Each one is a decision you make when you reach for sorting or search in real code — not a definition to recite, but a tradeoff to weigh.
Confirm you can connect the unit’s spine: sorting is preprocessing you pay for once, the O(n log n) sorts trade stability against memory and worst-case behaviour, and binary search generalises from arrays to any monotonic answer space.
You receive an unsorted array of 1,000,000 elements and need to answer exactly one membership query: is value X present? What is the cheapest correct approach?
You sort a list of orders by amount, where several orders share the same amount, and you need ties to stay in their original arrival order. Which sort is safe?
Merge sort and quicksort are both O(n log n) on average. For sorting a huge array in place under tight memory, with no stability requirement, why is quicksort often the production choice?
A quicksort that always picks the last element as pivot runs fine on random data but takes minutes on data that arrives already sorted. Why, and what is the standard fix?
A binary search uses while (lo < hi) with hi set to arr.length - 1 and returns -1 after the loop. It works on most inputs but misses the target when it sits at the position where lo equals hi. What is the defect?
You need the minimum ship capacity to deliver all packages within D days, with no sorted array of capacities to index. When can you still binary search?
The unit’s through-line is one habit: decide whether order is worth buying. Sort only when you reuse the order; pick a stable sort (merge, insertion) when ties must hold their place; trade merge sort’s O(n) buffer for quicksort’s in-place O(log n) stack when memory is tight, and accept that bad pivots risk O(n²) unless you randomize. Once order exists, binary search finds answers in O(log n) — but only with a correct inclusive invariant, and it generalises to any monotonic predicate, not just arrays.