Week 7: Searching Algorithms

Computer Algorithms (506994-002)

Ridho Hendra, Ph.D · Dept. of Intelligent Computing · Mon [1-3] · Building A, Room 703
Department of Intelligent Computing

Where We Are

Wk 1
Introduction
Wk 2
Algorithm Concepts
Wk 3
Complexity Analysis
Wk 4
Recursion & Recurrence
Wk 5
Basic Sorting
Wk 6
Advanced Sorting
Wk 7
Searching
Wk 8
Midterm Exam
Wk 9
Divide & Conquer
Wk 10
Greedy Algorithms
Wk 11
Dynamic Programming I
Wk 12
Dynamic Programming II
Wk 13
Graph Representation
Wk 14
Shortest Path
Wk 15
Final Exam
Department of Intelligent Computing

Last Week, This Week

  • Last week delivered: CampusNav's full 1,200-room directory can
    now be sorted efficiently - merge sort and quicksort replaced the
    O(n²) sorts that couldn't keep up at campus scale.
  • Last week left broken: sorting the directory didn't make
    finding a room in it any faster. Nothing in CampusNav's "jump to
    room" feature actually takes advantage of the fact that the list is
    now sorted.
Department of Intelligent Computing

Key Words Today

  • Search: given a target value and a collection, decide whether
    it's present and, if so, where.
  • Linear search: check items one at a time, in order, until found
    or exhausted.
  • Binary search: repeatedly halve the remaining search space -
    requires the data to be sorted first.
  • Loop invariant: a statement true before, during, and after every
    pass of a loop - today it's how we prove binary search correct,
    not just watch it work on examples.
Department of Intelligent Computing

"Jump to Room" Is Still Slow

CampusNav's directory is finally sorted alphabetically by building -
last week's work. But the "jump to room" button still does exactly
what it always did: it starts at the very top of the list and checks
every single entry, one after another, until it finds the room you
typed in. A student looking up a room near the end of the alphabet
still watches the app crawl through hundreds of entries it could,
in principle, skip straight past - the sorting didn't buy them
anything, because nothing in the app actually uses the fact that
the list is now in order.

Department of Intelligent Computing

The Gap the Sort Left Behind

"Jump to room," today (still scans top-down)
up to 1,200 checks
"Jump to room," if it used the sort order
about 11 checks
Illustrative, not measured data: the point is the gap, not the exact numbers.

The directory is sorted. The app just doesn't know how to use that yet.

Department of Intelligent Computing

What Else This Actually Costs

  • Every feature that looks something up - room lookup, a course-code
    check, a schedule query - inherits this same slow, top-down scan
    unless it's rebuilt to exploit sorted order.
  • Worse: a badly implemented "fast" search can look like it works
    in testing and still be wrong on real input - see the off-by-one
    pitfalls later today.
  • A search that silently gives the wrong answer is more dangerous
    than a slow one - a slow search is annoying, a wrong search is a bug
    no one notices until it's live.
Department of Intelligent Computing

The Same Bug, in Production

Not a hypothetical - this happened, to one of the most-used codebases on Earth.
In industry: binary search is one of the most common technical-interview questions of all time - and also one of the most commonly gotten wrong. A widely cited 2006 study of Java's own standard-library implementation found it had shipped a real off-by-one/overflow bug for roughly nine years before anyone caught it. "It's just halving a list" is deceptively easy to get subtly wrong.
Department of Intelligent Computing

This Week's Question

"Now that the directory is sorted, how do we search it fast - and how do we *prove*, not just observe, that it always finds the right answer?"
Department of Intelligent Computing

By the End of This Week, You Can

  1. Write linear search and binary search as precise pseudocode and
    state each one's Big-O.
  2. Prove binary search correct with a loop invariant: initialization,
    maintenance, and termination.
  3. Identify and fix the classic off-by-one bugs that break binary
    search implementations.
  4. Explain why binary search requires sorted input as a matter of
    correctness, not just speed.
  5. Apply Weeks 1-7 material - Big-O, recursion, sorting, searching -
    to midterm-style practice questions.
Department of Intelligent Computing

A Simple Idea, Surprisingly Hard to Get Right

Halving a sorted range to guess a hidden number is old. Getting the code right took decades.
  • The idea of halving a sorted search space dates back to at least
    1946 (John Mauchly, one of ENIAC's designers) - but the first
    published, fully correct
    version didn't appear until 1962. For 16
    years, working implementations existed alongside broken ones, and
    almost no one could tell the difference just by testing them.
  • Jon Bentley's Programming Pearls (1986) had professional
    programmers implement binary search; roughly 90% of their
    submissions contained a bug.
  • Even Java's own standard library shipped a subtle
    overflow bug in its binary search (mid = (lo + hi) / 2 can
    overflow for huge arrays) for about nine years before it was fixed
    in 2006.
Department of Intelligent Computing

What Sixteen Years of Bugs Actually Teach

Same history. The lesson it leaves behind.
The lesson isn't "binary search is hard." It's that an idea this simple still needs a real proof - "I tested it and it worked" was never enough, for anyone, including professionals.
Department of Intelligent Computing

The Search Problem, and Linear Search

Two searches to compare all week: the slow one you already know, and the fast one we're about to prove.

Given an array of elements and a target value, a search
algorithm decides whether the target occurs in and, if so,
returns its index.

Linear search - no sorting required, checks one entry at a time
(0-based indexing resumes here, after last week's 1-based exception):

LINEAR-SEARCH(A, target):
    for i = 0 to length(A) - 1:
        if A[i] == target:
            return i
    return NOT-FOUND
Department of Intelligent Computing

Key Words Today

  • 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.
Department of Intelligent Computing

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.

Department of Intelligent Computing

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
Department of Intelligent Computing

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.

Department of Intelligent Computing

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
Department of Intelligent Computing

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.

Department of Intelligent Computing

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:

  1. Assume the opposite of what you want to prove is true.
  2. Show that assumption leads to something impossible - a
    contradiction with a fact you already know.
  3. 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.

Department of Intelligent Computing

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.

Department of Intelligent Computing

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).

Department of Intelligent Computing
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.
Department of Intelligent Computing
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.
1
Round 1
lo=0, hi=6, mid=3. A[3]=40 < 60 → search right, lo=4.
→
2
Round 2
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.
Department of Intelligent Computing
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.
Department of Intelligent Computing
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.
→
2
Trace
lo=0,hi=4,mid=2: A[2]=30>10 → hi=1. lo=0,hi=1,mid=0: A[0]=50>10 → hi=−1. lo=0,hi=−1: loop ends → returns NOT-FOUND.
→
3
But it's right there
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.
Department of Intelligent Computing
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.
1
Round 1
lo=0, hi=15, mid=7. A[7]=802 > 703 → search left, hi=6.
→
2
Round 2
lo=0, hi=6, mid=3. A[3]=415 < 703 → search right, lo=4.
→
3
Round 3
lo=4, hi=6, mid=5. A[5]=615 < 703 → search right, lo=6.
→
4
Round 4
lo=6, hi=6, mid=6. A[6]=703 = target → **found, index 6**.
✓
ConclusionFound in 4 rounds. At the real 1,200-room scale, this is ~11 rounds - never up to 1,200.
💡
Key takeawayEvery round is one A[mid] comparison and one range-halving - exactly the loop invariant, executed.
Department of Intelligent Computing
CampusNav worked example 2 of 2

"Jump to Room": Target Absent

Same 16-entry array. This time, room code 550 doesn't exist.
GoalWatch the range shrink to empty instead of to a match.
1
Rounds 1-2
lo=0,hi=15,mid=7: A[7]=802>550 → hi=6. lo=0,hi=6,mid=3: A[3]=415<550 → lo=4.
→
2
Round 3
lo=4, hi=6, mid=5. A[5]=615 > 550 → search left, hi=4.
→
3
Round 4
lo=4, hi=4, mid=4. A[4]=512 < 550 → search right, lo=5.
→
★
Termination
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.
Department of Intelligent Computing

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.
Department of Intelligent Computing

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.
Department of Intelligent Computing

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?

Department of Intelligent Computing

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.

Department of Intelligent Computing

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.
Department of Intelligent Computing
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.
Department of Intelligent Computing

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.
Department of Intelligent Computing

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.

Department of Intelligent Computing

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.
Department of Intelligent Computing

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).
Department of Intelligent Computing

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.
Department of Intelligent Computing

Thank You

Department of Intelligent Computing

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

Dense worked example: midterm practice, Big-O / growth rate / recurrence

SLOT N+1: Limits (Act 4 / CLOSE), becomes Week 9's slot 4 (Week 8 is review-only)

SLOT N+2: Bridge

CLRS reference slide, immediately before Summary

SLOT N+3: Summary

SLOT N+4: Thank You