Courses / DSA Patterns for Working Engineers / Chapter 17
Module 5 · Cyclic sort, topological sort, and sort and search · Chapter 17 of 39
Sort and Search: Sort Once, Then Search Fast
Builds on Two Pointers: Pairs, Partitions and In-Place Scans, Top K Elements: Size-K Heaps, Buckets and Quickselect and Modified Binary Search: Bounds, Rotations and Searching the Answer. Next up: Matrices: Traversals, Rotations and In-Place Marking.
Part 1 · Introduction to sort and search
Pay for the order once
A billing system matches thousands of payments against a ledger, and a price tool checks thousands of quotes against a catalogue. Answering each question by scanning the whole list is slow, and sorting the list first can make every later question cheap.
The pattern has two steps. Sort the data once, which costs about n log n comparisons for n items. Then answer each question with a binary search, which halves the range at every probe and costs about log n. For q questions the total is roughly n log n + q log n, against q times n for scanning each time.
The sorted order also unlocks other methods. Two pointers walking inward from both ends work on sorted data, as the earlier chapter on them showed. A greedy rule that says "take the cheapest first" needs the data sorted by cost. Each lesson here sorts first and then uses one of those three: binary search, two pointers or a greedy scan.
Before the first lesson of problems, this one covers the tools: how to write a comparator correctly in JavaScript, what a stable sort promises, the two binary-search bounds used throughout, and a count of what sorting once buys. Code blocks follow the convention set out in the first chapter.