Lawfare Academy

CS 201 — Data Structures, Algorithms and Systems · Weeks 6–8

Sorting, binary search and boundary reasoning

Full teaching sequence and cumulative subject work

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.

Weighted shortest paths: implementation, proof and complexity — primary material, constructed-response tasks, complete worked model and changed-case examination →

Binary search on a half-open interval

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.

Trace the complete reasoning
  1. mid=2 holds 5, so hi=2. Equality does not justify returning immediately when the first match is required.

  2. mid=1 also holds 5, so hi=1. Then mid=0 holds 1, so lo=1. The interval is empty at [1,1).

  3. Return 1. Positions before 1 are below 5; the value at 1 is at least 5 and equals it, establishing membership.

  4. For target 10, return 4 and do not access items[4]. The wrapper reports absence after the bounds check.

Independent transfer problem

Give the lower bound and upper bound for 5 in the same list. Explain how to count duplicates without scanning them.

Compare the transfer solution

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.

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.

Study the mechanism

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 example

def lower_bound(items, target):
    lo, hi = 0, len(items)
    while lo < hi:
        mid = (lo + hi) // 2
        if items[mid] < target:
            lo = mid + 1
        else:
            hi = mid
    return lo

assert lower_bound([2, 4, 4, 9], 4) == 1
assert lower_bound([2, 4, 4, 9], 10) == 4

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.

Check your understanding

What precondition does binary search require?

  1. Ordering compatible with the search comparison
  2. Unique values only
  3. A fixed number of records known at compile time
Answer and reasoning for every option

Correct: Ordering compatible with the search comparison The interval exclusion argument depends on sorted order.

Reconsider: Unique values only Duplicates are permitted with a defined match policy.

Reconsider: A fixed number of records known at compile time Runtime-sized finite collections are compatible with binary search.

Transfer laboratory: Search for the last duplicate

For [2,4,4,4,9], find the insertion point after every 4. Explain how upper bound differs from lower bound, including the absent target 5.

Work through the full solution

Upper bound moves lo past values less than or equal to the target. It returns index 4 for target 4; lower bound returns 1. For 5 both return 4, so neither position alone proves a match. The half-open interval still shrinks to a boundary. Test empty input, all-equal input and targets outside the range.

Evidence of understanding

Return 4 and 1 appropriately and explain that insertion positions are not unconditional record indices.

Complete on-site teaching readings

These are full attributed source sections, not previews. Read them alongside the original Academy explanation and code.

  1. 11 . Sorting Algorithms · Pat Morin
  2. 11 . 1 Comparison-Based Sorting · Pat Morin
  3. 11 . 2 Counting Sort and Radix Sort · Pat Morin
  4. 11 . 3 Discussion and Exercises · Pat Morin

Open in My Learning to record progress →