Lawfare Group → Knowledge Institute → Lawfare Academy
← CS 201 — Data Structures, Algorithms and Systems
Weeks 6–8
Sorting, binary search and boundary reasoning
Learning objectives
- Explain and trace the mechanisms in sorting, binary search and boundary reasoning.
- Apply the method to the worked example and changed-condition exercise.
- Identify assumptions, failure cases and the evidence needed to justify a result.
- Test the added failure-mode fixture and explain which guarantee the evidence does and does not establish.
Binary search reduces a search interval by using ordering. Its correctness requires the data be sorted according to the same comparison rule used in the search. On an unsorted list, halving can discard the only match. Define whether you need any match, the first match or an insertion position; duplicates make these distinct problems.
A half-open interval [lo, hi) includes lo and excludes hi. Initially it spans all n elements with lo zero and hi n. A lower-bound search maintains that values before lo are less than the target and values at or after hi are at least the target. Each iteration shrinks the interval. When lo equals hi, that boundary is the first legal insertion position. Check whether it is within the list and equal before declaring a match.
Sorting also has contracts. Stable sorting preserves the relative order of equal-key records. Sorting by date and then by priority can differ from sorting by a compound key, depending on stability and intended precedence. Do not repeatedly sort a huge list just to answer isolated membership questions without evaluating a set or index. Logarithmic query cost may hide an earlier sorting cost.
Worked reasoning For target 4, mid initially points to the second 4, so hi becomes 2. The next midpoint is 1 and hi becomes 1. Position 0 is below the target, so lo becomes 1 and the loop ends. The result is the first 4. Target 10 produces len(items), a valid insertion boundary but not a valid element index.
Extended teaching and laboratory
Binary search is easier to reason about when the candidate interval is consistently half-open: [lo,hi). For lower_bound, maintain that every earlier position is below the target and every position at or beyond hi is at least the target. An equality moves hi left because an earlier equal value may exist. The interval shrinks until lo equals hi.
Returning an insertion position and proving a member exists are different tasks. A lower bound equal to len(items) is legal as a boundary and illegal as a direct element access. A membership wrapper must check both the boundary and equality. The precondition that the list is sorted under the same comparison rule is essential.
Worked problem Trace lower_bound for target 5 in [1,5,5,9], starting lo=0, hi=4 and mid=(lo+hi)//2.
Step-by-step reasoning 1. mid=2 holds 5, so hi=2. Equality does not justify returning immediately when the first match is required.
- mid=1 also holds 5, so hi=1. Then mid=0 holds 1, so lo=1. The interval is empty at [1,1).
- Return 1. Positions before 1 are below 5; the value at 1 is at least 5 and equals it, establishing membership.
- For target 10, return 4 and do not access items[4]. The wrapper reports absence after the bounds check.
Failure-oriented laboratory: Binary-search boundaries and duplicate keys
An algorithm specification includes behavior for duplicate keys and absent values. Finding any matching element differs from finding the first position at which a key could be inserted. A lower-bound search maintains a half-open interval [lo, hi) and discards only positions that cannot be the first element greater than or equal to the target. Equality must move the upper boundary, not return an arbitrary midpoint.
An invariant explains correctness: all positions below lo contain values strictly less than the target, while all positions at or above hi are known not to be the answer's missing earlier candidates. Each iteration shortens the undecided interval. At termination lo equals hi, identifying the boundary, including the valid one-past-end result. Dereferencing that position requires a separate bounds check.
Performance claims must identify operations and representation. Binary search makes logarithmically many comparisons on a sorted random-access sequence, but inserting into a Python list still shifts elements linearly. Maintaining sorted data can dominate lookup cost. Compare an append-and-sort batch with repeated sorted insertions under a stated workload rather than advertising one asymptotic number for the whole application.
Worked fixture
For [2, 2, 2, 5, 9], find lower-bound positions for targets 2, 4 and 10. Count a result of len(data) as valid.
Explain the fixture
The positions are 0, 3 and 5. Returning a middle 2 answers membership but not the first-occurrence contract. Position 5 is a valid insertion boundary for 10 but is not a valid index to dereference. Empty input must return 0 without accessing an element.
Apply the idea
Trace lower_bound for target 5 in [1,5,5,9], starting lo=0, hi=4 and mid=(lo+hi)//2.
Give the lower bound and upper bound for 5 in the same list. Explain how to count duplicates without scanning them.
Additional laboratory — Implement lower_bound without calling bisect, compare it with bisect_left for every target from −2 through 12 on empty, singleton, duplicate and sorted random fixtures. Separately benchmark lookup and insertion.
Read the worked reasoning
The lower bound is 1; the upper bound, first position greater than 5, is 3. Their difference is 2. Upper-bound search moves lo right when value is less than or equal to the target. Two logarithmic boundary searches count the equal range without traversing its elements; returning the actual elements would add output cost.
Additional laboratory model — Correctness evidence requires every expected position and the boundary invariant, not only a successful membership lookup. Compare generated fixtures with a fixed random seed and also hand-derived cases. Timing should disclose input size, repeat count and operation measured. Logarithmic comparisons do not imply logarithmic list insertion.
Check understanding
What precondition does binary search require?
- Ordering compatible with the search comparison
Feedback
The interval exclusion argument depends on sorted order.
- Unique values only
Feedback
Duplicates are permitted with a defined match policy.
- A fixed number of records known at compile time
Feedback
Runtime-sized finite collections are compatible with binary search.
Further reading
Preparation: study 2.1–2.4: sequences, growth and recurrences in the complete on-site Levin text. Attempt the investigation, work at least four exercises of increasing difficulty in each assigned section, and compare the selected hints/solutions only after a written attempt. Then complete the algorithm reading and implement the unit laboratory. For each algorithm give a specification, trace, correctness argument and time/space analysis.
- Oscar Levin — Discrete Mathematics: 2.1–2.4: sequences, growth and recurrences
- 11 . Sorting Algorithms
- 11 . 1 Comparison-Based Sorting
- 11 . 2 Counting Sort and Radix Sort
- 11 . 3 Discussion and Exercises
- Primary documentation for Binary-search boundaries and duplicate keys
- Academy — runnable synthetic lab kit and instructions