Precondition: something that must be true of the input for an
algorithm to be correct - not a performance nicety, a requirement.
lo, hi, mid: the three index pointers that track binary
search's current search range and its midpoint.
Off-by-one error: a bug caused by an index boundary being one
position too high or too low - often invisible until a specific
edge-case input triggers it.
Correctness proof: a demonstration that an algorithm produces
the right answer on every valid input, not a sample of inputs.
Linear Search: Best, Average, Worst
Best case: the target is the very first entry - 1 comparison.
Worst case: the target is the last entry, or absent entirely - comparisons.
Average case: roughly comparisons if the target is equally
likely to be anywhere.
None of these cases care whether is sorted - linear search works
(slowly) on any array, sorted or not. That flexibility is exactly what
we trade away to go faster.
Binary Search: Idea and Pseudocode
Guessing a hidden number 1-100 by always checking the middle of what's left - now on a sorted array. (CLRS - Cormen/Leiserson/Rivest/Stein's Introduction to Algorithms, 4th ed, Exercise 2.3-6)
If is sorted, you don't need to check every entry: check the middle one. Equal to target → done. Less than target →
it can only be in the left half - discard the right half. Greater
→ discard the left half. Repeat on whatever half remains. This
reasoning is only valid because is sorted.
BINARY-SEARCH(A, target):
lo = 0
hi = length(A) - 1
while lo <= hi:
mid = floor((lo + hi) / 2)
if A[mid] == target:
return mid
elif A[mid] < target:
lo = mid + 1
else:
hi = mid - 1
return NOT-FOUND
Why Binary Search Is O(log n)
Every comparison discards half of what's left. Starting from
elements:
This is the recurrence - constant work per
step, then recurse on half - the same halving pattern as Week 4's
recursion tree, just one subproblem per level instead of two.
Why Binary Search Is O(log n), the Levels
One subproblem per level, not two - so this table is shorter than Week 4's.
Level
Size
Cost at this level
0
1
2
Why Binary Search Is O(log n), Continued
The bound in numbers, for CampusNav's actual directory.
There are levels, each doing work, so O(log n).
For CampusNav's 1,200-room directory: .
Eleven comparisons, worst case, no matter where in the directory the
target sits - versus up to 1,200 for linear search.
A Quick Primer: Proof by Contradiction
One of today's proof's own moves, named before we lean on it.
A second proof technique, alongside loop invariants, shows up in a
moment - it has a simple, three-line shape:
Assume the opposite of what you want to prove is true.
Show that assumption leads to something impossible - a
contradiction with a fact you already know.
Conclude the original statement must be true after all, since
its opposite is impossible.
Tiny non-algorithmic example: there is no largest integer. Assume
there is one, call it . But is also an integer, and - contradicting " is the largest." So no largest
integer exists.
What We're Going to Prove
Not "it worked on the examples I tried." An actual proof.
Claim:BINARY-SEARCH above always returns the correct index if target is in A, and correctly reports NOT-FOUND otherwise - provided A is sorted.
The Loop Invariant
The one sentence the whole proof leans on. (Loop-invariant style per CLRS 4th ed, §2.1)
Loop invariant:
If target is present anywhere in A, then it is present within
the subarray A[lo..hi].
We prove this in three parts, exactly as Week 5 did for insertion
sort: initialization (true before the first pass), maintenance
(stays true across every pass), termination (what it tells us
when the loop stops).
Binary search · proving correctness
The Proof, All Three Parts
The invariant above holds on every trace we run today. Here is why it holds on every input, not just the ones we try.
GoalProve: BINARY-SEARCH is correct on every sorted input, not just the traces we draw.
1
Initialization
Before the loop: lo=0, hi=length(A)−1, so A[lo..hi] is the entire array. If target is present at all, it's trivially present somewhere in the whole array.
→
2
Maintenance
If A[mid]==target, return - correct. If A[mid]<target, sortedness means every index ≤ mid is ≤ A[mid]<target, so target (if present) is in A[mid+1..hi]: set lo=mid+1. Symmetric if A[mid]>target.
→
3
Termination
Either the loop returns mid with A[mid]==target (correct by construction), or lo>hi and A[lo..hi] is empty - so target cannot be present, and NOT-FOUND is correct.
★
Why all three parts
Initialization plus maintenance only show the invariant holds at the start of every iteration. Termination is what turns that into a claim about the finished search.
✓
ConclusionCorrect on every sorted input - not just the traces we draw below.
💡
Key takeawaySortedness is used explicitly in the maintenance step - break it, and the whole proof (not just the speed) collapses.
Binary search · worked example 1 of 3 (simple)
Seven Elements: Find 60
The smallest case that still needs more than one round.
GoalFind 60 in [10, 20, 30, 40, 50, 60, 70] and count the rounds.
lo=4, hi=6, mid=5. A[5]=60 = target → found at index 5.
→
3
Result
2 rounds to search 7 elements - matches ⌈log₂7⌉ = 3 as an upper bound, and beats it here because the target sat exactly on the second midpoint.
✓
ConclusionFound at index 5 in 2 rounds - linear search would have needed 6 comparisons for the same target.
💡
Key takeawayEvery round halves the range regardless of where the target sits - the worst case, not the lucky case, is what the O(log n) bound guarantees.
Binary search · worked example 2 of 3 (moderate)
Two Off-by-One Bugs, Traced
Two of the most common ways a correct-looking implementation breaks.
GoalTrace both classic off-by-one bugs and see exactly where each one fails.
1
Bug #1: setup
Array length 4. `hi` initialized to `length(A)`=4 (half-open convention) but the "greater" branch keeps `hi=mid-1` and `while lo<=hi` (closed-style). Target is larger than every element.
→
2
Bug #1: trace
lo=0,hi=4,mid=2→lo=3. lo=3,hi=4,mid=3→lo=4. lo=4,hi=4: `lo≤hi` still true → mid=4 → A[4] is read **out of bounds** (valid indices are 0-3).
3
Bug #2: setup and trace
The "greater" branch sets `lo=mid` instead of `lo=mid+1`. Suppose lo=4,hi=5,mid=4 and A[mid]<target: buggy code sets lo=mid=4 - unchanged. lo,hi never change again.
★
The fix
Bug #1: initialize `hi=length(A)-1` to match the closed convention used everywhere else. Bug #2: always `lo=mid+1` on this branch (its mirror, `hi=mid-1`, is already safe).
✓
ConclusionBug #1 reads out of bounds; Bug #2 loops forever - both come from one index boundary being one position off.
💡
Key takeawayAlways trace a 2-element range by hand to check your convention is self-consistent before trusting an implementation.
Binary search · worked example 3 of 3 (harder)
Unsorted Input: Silently Wrong, Not Just Slow
Not a performance caveat - a correctness one.
GoalRun BINARY-SEARCH on unsorted data and see it report a present element as missing.
1
Setup
A = [50, 10, 30, 90, 5] - unsorted. Target = 10, which *is* present, at index 1.
10 sits at index 1 the entire time. The maintenance proof relied on "everything ≤ mid is ≤ A[mid]" - true only when A is sorted, and false here.
★
Why this matters more than speed
This isn't a slow answer - it's a wrong one, with no crash or error to flag it. Sortedness is part of the correctness proof itself, not a performance footnote.
✓
ConclusionBinary search on unsorted data can silently report a present element as missing.
💡
Key takeaway"Sorted-looking" is not good enough - the proof needs every index ≤ mid to be ≤ A[mid], which one out-of-order pair anywhere can break.
CampusNav worked example 1 of 2
"Jump to Room": Target Found
Everything above, on real (sample) directory data.
GoalA 16-entry sorted sample of CampusNav's directory, searching for room code 703.
Now lo=5, hi=4: lo>hi, the loop condition fails → **returns NOT-FOUND**. Same 4 rounds as finding 703 - just ending in the other exit.
✓
ConclusionThe range shrank to empty without ever matching - by the invariant, 550 provably isn't in A.
💡
Key takeawayThis is the termination proof's second case, made concrete: an empty range is itself the proof of absence.
Common Mistakes
Off-by-one bound updates: using hi = mid instead of hi = mid - 1 (or the reverse mix), or lo = mid instead of lo = mid + 1 - each either skips a valid index or loops forever.
See the two pitfalls above; always trace a 2-element range by hand
to check your convention is self-consistent.
Assuming it works on unsorted data: binary search's entire
maintenance argument depends on sortedness. Running it on unsorted
input doesn't just risk being slow - it can silently report a
present element as missing, with no error or crash.
Key Words Today
Midterm scope: Weeks 1-7 - algorithm properties, complexity
analysis, recursion/recurrences, basic and advanced sorting, and
today's searching content.
Recurrence: an equation defining a recursive algorithm's cost in
terms of smaller instances of itself (Week 4) - part of today's
practice set.
Growth-rate ordering: ranking functions by how fast they grow as (Week 3) - also on today's practice set.
Midterm Review: Weeks 1-7
This block reviews everything Weeks 1-7 established, worked directly
rather than left as a question - the same driving question, one level
up: what does this course need you to prove, trace, and analyze so far?
What's In Scope
Wk
Topic
What you should be able to do
1
Introduction
Explain correct vs. efficient as separate, provable claims
2
Algorithm Concepts
Check pseudocode against the five required properties
3
Complexity Analysis
Prove a Big-O bound formally; order growth rates
4
Recursion & Recurrence
Write and solve a recurrence (recursion tree / substitution)
5
Basic Sorting
Trace insertion/selection/bubble sort; write a loop-invariant proof
6
Advanced Sorting
Trace merge sort/quicksort; state best/avg/worst case and why
7
Searching
Trace binary search; write its loop-invariant proof; spot off-by-ones
Nothing on the midterm is new - every question below reuses a
technique from a week you've already sat through.
What to Expect
Format: a mix of short written proofs, hand traces, and a few
multiple-choice / short-answer items - no live coding.
Weight: 25% of the final grade (see Week 1's grading table).
The single best predictor of doing well: being able to redo,
from scratch, every worked example and proof already shown in
Weeks 1-7 - not just recognize them.
What follows now: one worked practice set, covering formal
reasoning skills from Weeks 3-4 that this week's own content didn't
otherwise exercise - a full week-by-week review lives in Week 8.
Midterm practice
Big-O, Growth Rate, and Recurrences
Three formal-reasoning skills from Weeks 3-4, worked directly.
GoalProve a Big-O bound, order growth rates, and solve a recurrence - all three, correctly.
1
Big-O proof
Show 3n² + 5n + 2 = O(n²): for n ≥ 1, n ≤ n² and 1 ≤ n², so 3n²+5n+2 ≤ 3n²+5n²+2n² = 10n². Constants c=10, n0=1 satisfy the definition.
2
Growth-rate order
Slowest to fastest, as n→∞: log n < n < n log n < n^2 < 2^n < n!. Each grows strictly faster than every function before it, eventually.
3
Solve a recurrence
Merge sort's T(n) = 2T(n/2) + n: recursion-tree method gives log₂n levels, each totaling n work → n log₂n, i.e. O(n log n).
★
Why all three together
Bounding, ordering, and solving are the three formal-reasoning skills the midterm tests beyond hand-tracing - each reused, unchanged, from Weeks 3 and 4.
✓
ConclusionEvery one of these three techniques reappears, unchanged, on the midterm - practice them exactly as shown here.
💡
Key takeawayA full per-week recap, with practice problems for Weeks 1-7 individually, is Week 8's entire session.
What Weeks 1-7 Still Cannot Do
Big-O, recursion, sorting, and searching are all in place - CampusNav
can now sort and search its directory correctly and efficiently. But
every technique so far has been ad hoc per problem: a different
trick for sorting, a different trick for searching, each invented and
proved one at a time. There is still no general strategy for
inventing a new algorithm when CampusNav's next feature doesn't
already have a known technique to reach for.
Next Week
Week 8 is the Midterm Exam, covering everything in Weeks 1-7 -
review using the practice set above and your Week 1-7 handouts. Week 9 begins Divide and Conquer, the first of this course's
general problem-solving paradigms: it addresses exactly what Week 7
leaves unsolved - a repeatable strategy for building a new efficient
algorithm, not just applying ones we already have.
Where This Week Lives in CLRS
A map, for anyone reading alongside the lectures.
Topic
CLRS 4th ed
Loop-invariant proof style (used for binary search today)
§2.1
Binary search
Exercise 2.3-6
If you want to go deeper: CLRS Ch 12 (Binary Search Trees) is
the natural next structure once linear search of a sorted array
feels limiting - a data structure built so that "search," "insert,"
and "delete" are all fast, not just search. Not required for this
course, but a preview of where sorted-order search ideas go next.
Also worth a look: CLRS §2.3 (merge sort) and Ch 7 (quicksort) from
Week 6 are the two techniques that got CampusNav's directory sorted
in the first place - this week's binary search only works because
of that earlier work.
Summary
Binary search is fast (O(log n)) but only correct when its
precondition - sorted input - actually holds; violating it isn't
slower, it's wrong.
A loop invariant (init / maintenance / termination) is how we prove
an algorithm correct on every input, not just the ones we tried -
the same pattern Week 5 used for insertion sort.
Off-by-one bugs in bound updates (hi = mid vs. mid - 1, lo = mid vs. mid + 1) are the single most common way binary search
breaks - trace a 2-element range by hand to check your convention.
New: Week 7 Check - a short graded exercise on linear search,
binary search, and its correctness proof, released now, due before
Week 8 begins (see materials/assignments/week07-check.html).
Summary, Continued
Reading: CLRS 4th ed, review §2.1 (loop-invariant style) and
Exercise 2.3-6 (binary search) - see the CLRS map above; Sedgewick, Algorithms, §1.1 has a full correctness discussion if you want a
second treatment.
Prepare for Week 8: rework every proof and trace from Weeks 1-7
from scratch, on paper, without looking at the slides first.
Thank You
SLOT 1: Title
notes: Open by noting: last week we sorted CampusNav's entire room directory. Sorting it did not, by itself, make the app any faster to *search* - nothing in the app yet uses the fact that it's sorted.
SLOT 2: Where we are
notes: Point at Wk 7, then at Wk 8. Say: "This is also the last new material before the midterm - everything from here connects back to Weeks 1 through 6."
SLOT 3: Recap + open wound
Key Words Today, session 1
notes: Read each term aloud. Say: "By the end of today, 'binary search' stops being a trick and becomes something we can prove."
SLOT 4: The pain (Act 1 / MOTIVATE), zero jargon
notes: Do not say "binary search" or "O(log n)" yet. Let the class notice the sorted-but-still-slow gap themselves.
notes: Pause on the second bar. This is the whole week's payoff, shown before any code.
SLOT 5: Cost of not knowing
SLOT 6: Driving question
SLOT 7: Learning outcomes
SLOT 8: Origin
SLOT 9: Core concept
Key Words Today, session 2
notes: Read each term aloud. Say: "Today's proof puts a precise meaning behind every one of these words."
Act 3 / BUILD
binary search cost, continued - CampusNav example
Dense flagship: binary search correctness, all three parts
Dense worked example, binary search, simple tier
Dense worked example, binary search, moderate tier (off-by-one pitfalls)
Dense worked example, binary search, harder tier (sortedness precondition)
SLOT N-2: Worked example
SLOT N-1: Common mistakes
Key Words Today, session 3
notes: Read each term aloud. Say: "What's left today is entirely midterm prep - the same rigor, applied to everything so far."
Midterm Review mini-block: extra Act-3 content, pre-midterm week