The Lawfare Academy

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.

Original on-site study sequence

Study this preserved lesson with the expanded original reader linked in Further reading. It supplies mathematical preparation, advanced representations, complete original and changed models, the Cedar cumulative investigation and a 24-point rubric. Use the resource-safe laboratory edition for optional local execution. All older publisher and textbook links are optional references. Current whole-course internal review remains pending.

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.

  1. mid=1 also holds 5, so hi=1. Then mid=0 holds 1, so lo=1. The interval is empty at [1,1).
  1. Return 1. Positions before 1 are below 5; the value at 1 is at least 5 and equals it, establishing membership.
  1. 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.

Integrated application: implementation, debugging and local deployment

The complete service-company project is now part of this unit’s applied work. It supplies an inspectable browser interface, HTTP server, persistent SQLite ledger, transaction tests, export recovery, permission-scoped retrieval and a separate synthetic logistic evaluation pipeline. Begin with its actual test suite, then trace one user request from UI to storage and back. The README distinguishes the local teaching environment from a production deployment.

Course-specific investigation

Implement lower-bound lookup over a sorted event-ID snapshot and a hash-index alternative. Check empty, duplicate, missing and one-past-end cases. Measure sorting/index construction separately from lookup, using the same fixture and disclosed repetitions.

What the evidence must establish

The fastest lookup alone may not minimize total workload cost. State update frequency, query count, memory use and construction costs; validate every result against a simple independently understood reference.

Keep a reproducibility log with Python version, launch command, fixture, expected result, observed result and explanation of any discrepancy. Introduce one deliberate defect and show the corresponding failing test before restoring the implementation. Passing an existing test without explaining its boundary is insufficient. The integration project remains optional practice rather than a mandatory capstone submission.

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.

Complete-application investigation: Implement lower-bound lookup over a sorted event-ID snapshot and a hash-index alternative. Check empty, duplicate, missing and one-past-end cases. Measure sorting/index construction separately from lookup, using the same fixture and disclosed repetitions.

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.

Application reasoning model: The fastest lookup alone may not minimize total workload cost. State update frequency, query count, memory use and construction costs; validate every result against a simple independently understood reference.

Check understanding

What precondition does binary search require?

  1. Ordering compatible with the search comparison
    Feedback

    The interval exclusion argument depends on sorted order.

  2. Unique values only
    Feedback

    Duplicates are permitted with a defined match policy.

  3. A fixed number of records known at compile time
    Feedback

    Runtime-sized finite collections are compatible with binary search.

Further reading

Study the original native lesson and expanded on-site reader. Work through the relevant mathematical and representation mechanisms, then the complete Cedar original/changed investigation and rubric. The retained workbook and weighted-path model provide further original practice. All practice and source references are optional; no external chapter or exercise is required.

My learning →