Proving a bound, then finding exactly where one term overtakes another.
GoalProve 3n² + 20n + 100 = O(n²), then find where n² overtakes 100n.
1
The proof
For n ≥ 1: n ≤ n² and 1 ≤ n², so 3n²+20n+100 ≤ 3n²+20n²+100n² = 123n². Constants c=123, n0=1 satisfy the definition.
→
2
The crossover
For 100n vs. n²: solving n² > 100n gives n > 100. Below n=100, 100n is actually the larger value.
→
3
Why the crossover matters
It's exactly why a Big-O claim is stated as "for all n ≥ n0," not "always, no matter how small n is" - n0=101 would also be a valid witness for "n² dominates 100n."
★
The witnesses aren't unique
c and n0 are witnesses to the bound, not "the" constants - any larger valid c, or any n0 past the crossover, also works.
✓
Conclusionc=123, n0=1 proves the bound; n=100 is the concrete point past which n² wins outright.
💡
Key takeawayA Big-O proof and a crossover calculation are two different tools - the first proves a bound holds eventually and forever, the second finds exactly when.
Common Midterm Mistake: Complexity Analysis
Misconception 1: " means the algorithm takes exactly steps." Reality: Big-O is an upper bound on growth
rate - it says cost grows no faster than , not that it equals
some fixed multiple of .
Misconception 2: given , keeping the term
"because 100 is a bigger number." Reality: the dominant term is
decided by growth rate as - eventually outgrows for any fixed constant - not by which coefficient looks
bigger for small .
Recap: Week 4 - Recursion & Recurrence
Tracing and bounding cost that calls itself.
A recursive algorithm's cost is described by a recurrence: cost
on size in terms of cost on smaller sizes, plus the non-recursive
work at that step.
Solving a recurrence (recursion-tree or substitution method) turns
"" into a closed-form bound like .
The recursion tree's depth (how many times the input shrinks
before hitting the base case) is what bounds the total work - the
base case is not "just where you stop," it's half of what determines
that depth.
Midterm practice · Week 4
Solving a Recurrence, Then Comparing One
Merge sort's own recurrence, then a second one to contrast against it.
GoalSolve T(n) = 2T(n/2) + n, then compare it to T(n) = T(n−1) + O(1).
1
Solve the merge-sort recurrence
Each of log₂n levels splits into 2 subproblems of half the size, but combine work still totals n per level (level 0: n, level 1: 2·(n/2)=n, ...). Sum: n log₂n → Θ(n log n).
2
Solve the tour-time recurrence
T(n) = T(n−1) + O(1), from Week 4's tour-time example: unrolls to n constant-cost steps, one per stop → O(n).
3
Compare structurally
O(n) is much cheaper than O(n log n) - but not because "subtracting 1 is always faster than halving." It's because depth n with O(1) work/call, vs. depth log n with O(n) work/level - depth alone never tells you total cost.
★
The reusable lesson
Always identify BOTH the recursion tree's depth and the work done per level before claiming a bound - one without the other is an incomplete argument.
✓
ConclusionT(n)=2T(n/2)+n → Θ(n log n). T(n)=T(n−1)+O(1) → O(n) - a smaller bound, for structural reasons, not because recursion "got faster."
💡
Key takeawayDepth and per-level cost are both required inputs to a recurrence's solution - never just one.
Common Midterm Mistake: Recursion & Recurrence
Misconception 1: "Recursion is always less efficient than
iteration." Reality: a recursive algorithm's efficiency is decided
by its recurrence, not by the fact that it calls itself - merge sort's resolves to the same whether written
recursively or converted to an iterative bottom-up version.
Misconception 2: "The base case is just where you stop." Reality: the base case, combined with how fast the input shrinks
each call, determines the recursion tree's depth - exactly what
you sum over to get total cost. Get either one wrong, and the whole
cost bound changes.
Recap: Week 5 - Basic Sorting
Provably correct, at O(n²).
Bubble, selection, and insertion sort are all worst case -
but not interchangeable: only bubble and insertion sort are
adaptive (fast on nearly-sorted input) and stable (equal keys keep
relative order); selection sort is neither.
Insertion sort is proven correct with a loop invariant:
initialization, maintenance, termination - the exact three-part
structure every later correctness proof in this course reuses.
Stability isn't cosmetic - it's what makes multi-key sorting (sort by
column A, then column B) actually work.
Midterm practice · Week 5
A Stability Trace, and a Real-World Pick
Two directory entries tie on sort key 2 - call them 2a (entered first) and 2b (entered second).
GoalTrace insertion sort on [4, 2a, 3, 2b] and pick the fastest sort for a near-sorted update.
1
The trace
start
4
2a
3
2b
ins 2a
2a
4
3
2b
ins 3
2a
3
4
2b
ins 2b
2a
2b
3
4
→
2
Stability holds
2a stays before 2b: insertion sort only shifts elements *strictly greater* than the key, so equal keys never cross - stable in general, not just here.
3
The real-world pick
A 500-entry, already-alphabetized directory gets one new room added near the end. Insertion sort (or bubble sort, with its early-exit flag) finishes fastest - both are adaptive.
★
Why selection sort loses here
Selection sort gives no such benefit: its inner loop always scans the entire remaining unsorted region regardless of how close to sorted the array already is.
✓
Conclusion[4, 2a, 3, 2b] → [2a, 2b, 3, 4], order preserved; and adaptive sorts (insertion, bubble) win on nearly-sorted real data.
💡
Key takeawayThe same "strictly greater" comparison that gives insertion sort its stability is also what lets it detect and exploit a nearly-sorted array.
Common Midterm Mistake: Basic Sorting
Misconception: "All three sorts behave identically, since
they share the same worst-case bound." Reality: the worst-case
bound matches, but their personalities don't: selection sort always
makes exactly swaps and never adapts to nearly-sorted input;
bubble and insertion sort can finish in close to on
nearly-sorted data; and only bubble and insertion sort are stable. A
question that only asks for the worst-case Big-O is not testing the
whole picture.
Recap: Week 6 - Advanced Sorting
Escaping O(n²) - two different ways.
Merge sort: always - best, average, and worst
case - because it always splits exactly in half; pays
auxiliary space and allocates new arrays every MERGE call.
Quicksort: in-place, expected, but worst
case if the pivot strategy is predictable (e.g. always the last
element, on already-sorted data).
Pivot choice (random, median-of-three) is what fixes quicksort's
worst case - the partition scheme (Lomuto/Hoare) is a separate
decision from pivot strategy.
Midterm practice · Week 6
Quicksort's Worst Case, and When to Avoid It
CampusNav's directory is already sorted, and someone re-runs quicksort on it, always choosing the last element as pivot.
GoalState the running time, why, a fix - and when to reach for merge sort instead.
1
The running time
O(n²). On already-sorted data, the last element is always the largest remaining - every partition splits into one subproblem of size n−1 and one of size 0: n levels of O(n) work, not log n levels.
→
2
The fix
Choose the pivot randomly (or median-of-three), so an adversarial or already-sorted input can't force the worst split.
3
When to prefer merge sort instead
A real-time system needing a **guaranteed** worst-case bound, where stability doesn't matter: merge sort's O(n log n) holds in the best, average, and worst case, because its divide step always splits exactly in half.
★
The misconception this kills
"Quicksort's O(n²) worst case is rare enough to ignore" - it isn't rare by construction, since already- or reverse-sorted data is an entirely ordinary shape for real input.
✓
ConclusionFixed last-element pivot on sorted data: O(n²). Fix the pivot strategy, or choose merge sort when the guarantee itself is the requirement.
💡
Key takeaway"Faster on average" and "safe to rely on" are different claims - only a worst-case bound answers the second one.
Common Midterm Mistake: Advanced Sorting
Misconception: "Quicksort's worst case is so rare in
practice it can be ignored." Reality: it isn't rare by
construction - a first- or last-element pivot strategy hits
on any already-sorted or reverse-sorted input, an entirely ordinary
shape for real data (e.g. re-sorting an already-mostly-sorted
directory after a small update). The fix is the pivot strategy, not
hoping the input stays "random."
Recap: Week 7 - Searching
Making the sorted directory earn its keep.
Linear search works on any array, sorted or not, in - binary
search needs sorted input but runs in .
Binary search's loop invariant: "if target is present in , it
is present within A[lo..hi]" - proven with initialization,
maintenance, termination, the exact three-part shape Week 5 used for
insertion sort.
Sortedness is a correctness precondition, not just a speed one:
running binary search on unsorted data can silently return the wrong
answer, not just a slow one.
Midterm practice · Week 7
The Invariant, and Why It Always Terminates
State the invariant, use it to explain sortedness, then show termination on a narrow range.
GoalState binary search's invariant and confirm the loop always reaches an exit.
1
The invariant
If the target is present in the array, it lies within the current search window [lo, hi]. Before the loop, the window is the whole array - trivially true.
→
2
Why sortedness is required
Each step discards the half that provably cannot contain the target, based on one comparison against the midpoint - only valid if everything in that half is known to be on the wrong side of the target.
→
3
Narrow-range termination
An 8-element search narrows to lo=3, hi=3 without returning yet. One more round runs: mid=3, A[3] is checked directly. Either it matches (return 3), or lo becomes 4 or hi becomes 2 - either way lo>hi next, and the loop exits.
★
What this proves
The loop always reaches a single-element range before it can run out of room to shrink into - exactly the shrinking argument the termination proof relies on.
✓
ConclusionThe invariant plus the shrinking-range argument together guarantee both correctness and termination, on every sorted input.
💡
Key takeaway"Provably cannot contain the target" is exactly where sortedness is required - on unsorted data the invariant simply breaks.
Common Midterm Mistake: Searching
Misconception 1: off-by-one bound updates - using hi = mid
instead of hi = mid - 1, or lo = mid instead of lo = mid + 1 -
either skips a valid index or loops forever. Always trace a 2-element
range by hand to check your convention is self-consistent.
Misconception 2: "binary search will just be slow on unsorted
data, like a worse linear search." Reality: it can be wrong,
silently reporting a present element as missing - the maintenance
proof's core step ("everything mid is ") only holds
when is actually sorted.
Synthesis · recursion & recurrences
Same Shape, Different Bound
A recursive algorithm halves the input each call but does only constant work per call - no combine step.
GoalSolve T(n) = 2T(n/2) + O(1), and compare it honestly to merge sort's recurrence.
1
Build the tree
Level k has 2^k nodes, each of size n/2^k, each doing O(1) work - so level k costs O(2^k). Depth is log₂n.
→
2
Sum the series
∑ (k=0 to log₂n) O(2^k) = O(2^(log₂n + 1)) = O(n) - a geometric series dominated by its last (bottom) level alone.
→
3
Compare to merge sort, correctly
Merge sort's T(n)=2T(n/2)+O(n) gives Θ(n log n) - strictly larger than this recurrence's O(n), even though both share a=2, b=2. The difference is entirely in f(n): O(1) here vs. O(n) for merge sort.
★
The lesson
This one is dominated by the bottom level's sheer node count; merge sort's is spread evenly across every level. Same recurrence *shape* (2, halve) does not mean same bound - always redo the sum.
✓
ConclusionT(n) = 2T(n/2) + O(1) resolves to O(n) - smaller than merge sort's Θ(n log n), because the per-call work differs, not the branching factor.
💡
Key takeawayTwo recurrences that look similar can land on different bounds through very different mechanisms - never pattern-match by shape alone.
Synthesis · sorting, Weeks 5-6
Choosing a Sort for Reverse-Sorted Bulk Data
CampusNav's 1,200-entry directory needs re-sorting after a bulk import that leaves it almost entirely reverse-alphabetized.
GoalRecommend a sort - and name the one to specifically avoid.
1
Avoid: insertion sort
Its adaptiveness only helps on *nearly-sorted* input; a nearly reverse-sorted array is close to its actual worst case, where every new key shifts almost the entire sorted prefix.
2
Also avoid: fixed-pivot quicksort
Reverse-sorted input is exactly the adversarial shape that forces first- or last-element-pivot quicksort's O(n²) worst case - mirroring the already-sorted example from Week 6.
3
Best choice
Merge sort, or quicksort with a random or median-of-three pivot - both guarantee (or expect) O(n log n) regardless of whether the input arrives sorted, reverse-sorted, or anything in between.
★
The general pattern
Whenever an input's *shape* (not just its size) can be adversarial, prefer whichever algorithm's guarantee doesn't depend on that shape.
✓
ConclusionAvoid insertion sort and fixed-pivot quicksort here; merge sort or randomized/median-of-three quicksort are both safe.
💡
Key takeaway"Adaptive" and "guaranteed" are different properties - reverse-sorted data is exactly where the difference shows up.
Synthesis · sorting & searching together
Why Sorting Must Fully Precede Searching
CampusNav could try to binary-search its directory without fully sorting it first, by spot-checking "does this half still look ordered" at each step, falling back to linear scan if not.
GoalShow what's wrong with this plan, as a matter of correctness, not just speed.
1
What the proof actually requires
Binary search's maintenance proof relies on *every* index ≤ mid being ≤ A[mid], across the entire current range - not a spot-check of one or two boundary values.
→
2
Where the heuristic fails
A "looks ordered" heuristic can pass on a range that isn't actually fully sorted - e.g. a single out-of-order pair buried in the middle, with both ends still looking fine.
→
3
The consequence
That silently breaks the exact assumption the proof depends on - the search can return the wrong answer with no warning, exactly like running it on genuinely unsorted data.
★
Why Weeks 5-6 had to come first
There is no cheaper substitute for genuine, full sortedness as a precondition - which is exactly why sorting had to be fully solved before Week 7 could touch searching at all.
✓
ConclusionA spot-check heuristic cannot replace genuine full sortedness - the maintenance proof needs the whole range, not just its ends.
💡
Key takeawayA precondition that's "probably true" is not the same as one that's proven true - the proof doesn't run on probabilities.
Synthesis · proof structure
One Proof Shape, Two Algorithms
Insertion sort's loop invariant (Week 5) and binary search's loop invariant (Week 7) both use the same three-part structure.
GoalState one genuine similarity and one genuine difference between the two proofs.
1
The similarity
Both use initialization (true before the loop starts, usually trivially), maintenance (each iteration preserves the invariant, argued case by case), and termination (what the invariant implies once the exit condition is reached).
→
2
The difference
Insertion sort's invariant describes what's *true of a growing region* (A[0..i-1] is sorted) - termination confirms the whole array ended up in the claimed state, a positive confirmation.
→
3
The opposite direction
Binary search's invariant describes what's *still possible* ("if target is present, it's in A[lo..hi]") - a claim that gets narrower over time, and termination *rules out* a possibility rather than confirming a positive state.
★
Same tool, opposite use
Recognizing which direction a given invariant runs is often the fastest way to see what its termination step is actually proving.
✓
ConclusionSame three-part shape, one proof builds a positive claim, the other narrows toward ruling a possibility out.
💡
Key takeawayLearn the shape once, then ask "is this invariant building something, or eliminating something?" for any new proof you meet.
What to Focus On Next
Weeks 1-7 gave you a toolkit: correctness, complexity, recursion,
sorting, searching. Weeks 9-14 don't add more of the same kind - they
teach four general strategies for inventing new algorithms, plus
how to represent networks at all.
Wk 9
Divide & Conquer
›
Wk 10
Greedy Algorithms
›
Wks 11-12
Dynamic Programming I & II
›
Wks 13-14
Graphs & Shortest Path
Nothing here is graded today - just orient yourself for what's next.
Next Week
Week 8 is the checkpoint. Week 9 begins Divide and Conquer - the
first of four general strategies for inventing new algorithms.
Summary
Weeks 1-7 built one connected toolkit, not seven separate topics:
correctness/complexity vocabulary, recursion, and the two classic
building blocks - sorting and searching - all examined through
CampusNav's directory/lookup features.
Today was a checkpoint, not new material: use the Coverage list, the
per-week recap cards, worked practice problems, and common-mistake
warnings above to find your own gaps before the exam.
Summary, Continued
Reading: review CLRS (Cormen/Leiserson/Rivest/Stein's Introduction to Algorithms) 4th ed, Chapters 1-4 (algorithm properties,
analyzing algorithms, growth of functions, recursion/recurrences),
§2.1-2.2 (basic sorting), §2.3 and Ch 7 (advanced sorting), and
Exercise 2.3-6 (binary search) - skim what you've already read, no
new reading assigned.
Prepare: Assignment 2 (Sorting) is due before the exam per the
syllabus; bring only what the instructor's exam announcement
permits. No separate Week 8 Check is issued - the worked practice
above, plus the midterm itself, cover this week.
Thank You
SLOT 1: Title
notes: This is a short review deck, not a lecture. No new material today -
walk through the review directly, answer questions, then hand off to the exam itself.
SLOT 2: Where we are
notes: Point at Week 8. Say: "Seven weeks of toolkit, checked today. No new material - this is the checkpoint."
SLOT 3: Recap (Act 0 / LOCATE) - one line per topic-block, Weeks 1-7. No open-wound sentence: short review variant carries no Pain/Ground act.
Before the Exam: generic logistics, no invented room/date/time
Act 3 / BUILD, expanded per SPINE's short-review variant
Act 3: Coverage
Week 1 review block
Dense worked practice: Week 1
Week 2 review block
Dense worked practice: Week 2
Week 3 review block
Dense worked practice: Week 3
Week 4 review block
Dense worked practice: Week 4
Week 5 review block
Dense worked practice: Week 5
Week 6 review block
Dense worked practice: Week 6
Week 7 review block
Dense worked practice: Week 7
Cross-cutting synthesis 1
Cross-cutting synthesis 2
Cross-cutting synthesis 3
Cross-cutting synthesis 4
SLOT N+1: replaces "Limits" per SPINE's short-review variant