Algorithms - Complete Interactive Lesson
Part 1: Core Concepts
⚙️ Algorithms
Part 1 of 7 — Sequencing, Selection, Iteration, and Algorithm Analysis
What Is an Algorithm?
An algorithm is a finite set of step-by-step instructions for solving a problem or accomplishing a task. Every algorithm is built from three fundamental building blocks:
| Building Block | Description | Pseudocode |
|---|---|---|
| Sequencing | Steps executed in order, one after another | Line 1, then Line 2, then Line 3 |
| Selection | A decision point — choose a path based on a condition | IF / ELSE |
| Iteration | Repeat a set of steps | REPEAT, REPEAT UNTIL |
🔑 Any computable problem can be solved using just these three building blocks. This is a fundamental principle of computer science.
Algorithm Efficiency
Not all algorithms solve a problem equally fast. Efficiency measures how the number of steps grows as the input size grows.
| Algorithm | Steps for n items | Classification |
|---|---|---|
| Linear search | Up to n steps | Reasonable |
| Binary search | Up to log2(n) steps | Reasonable |
| Bubble sort | Up to n x n steps | Reasonable (but slow) |
| Checking all subsets | 2^n steps | Unreasonable |
| Checking all orderings | n! steps | Unreasonable |
Reasonable algorithms run in polynomial time (n, n squared, n cubed). Unreasonable algorithms run in exponential or factorial time (2^n, n!).
Concept Check 🎯
Searching Algorithms
Linear Search
Check each element one by one from start to end.
PROCEDURE linearSearch(list, target)
{
FOR EACH item IN list
{
IF (item = target)
{
RETURN true
}
}
RETURN false
}
- Works on any list (sorted or unsorted)
- Worst case: check all n items
Binary Search
Repeatedly divide a SORTED list in half.
PROCEDURE binarySearch(sortedList, target)
{
low ← 1
high ← LENGTH(sortedList)
REPEAT UNTIL (low > high)
{
mid ← (low + high) / 2
IF (sortedList[mid] = target)
RETURN mid
ELSE IF (target < sortedList[mid])
high ← mid - 1
ELSE
low ← mid + 1
}
RETURN -1
}
- Requires a sorted list
- Each step eliminates half the remaining items
- Much faster for large datasets
Decidable vs Undecidable Problems
- Decidable: An algorithm exists that always produces a correct yes/no answer
- Undecidable: No algorithm can solve it for ALL possible inputs (e.g., the Halting Problem)
Applied Recall ✍️
-
Binary search requires the list to be _______ before searching.
-
An algorithm that takes 2^n steps for n inputs is classified as _______ (reasonable or unreasonable).
-
A problem for which no algorithm can produce a correct answer for ALL inputs is called _______.
Compare Algorithms 🔍
AP Exam Strategy: Algorithms
- Know the difference between linear search (unsorted, n steps) and binary search (sorted, log2(n) steps)
- Reasonable = polynomial (n, n squared). Unreasonable = exponential or factorial (2^n, n!)
- Heuristic algorithms find "good enough" solutions when optimal is unreasonable
- The Halting Problem is the key example of an undecidable problem — no program can determine if another program will halt for ALL inputs
- Every algorithm uses sequencing, selection, and/or iteration
AP-Style Application 🎯
Part 2: Key Processes
⚙️ Algorithms
Part 2 of 7 — Key Processes
How Algorithms Execute Step by Step
An algorithm is a finite, ordered sequence of unambiguous steps. On the AP CSP exam you will trace pseudocode by hand. Master three control flows and you can trace anything.
| Construct | What it does |
|---|---|
| Sequence | Statements run top to bottom, exactly once. |
| Selection | IF / ELSE chooses between branches. |
| Iteration | REPEAT N TIMES or REPEAT UNTIL runs a block multiple times. |
AP pseudocode rule: assignment uses a ← 5. Comparison uses =. Lists are 1-indexed.
Concept Check 🎯
Tracing a Loop by Hand
n ← 4 total ← 0 REPEAT n TIMES { total ← total + n n ← n − 1 } DISPLAY(total)
Key trick: the loop count for REPEAT n TIMES is fixed when the loop starts (n = 4), even if n changes inside.
| Iteration | total before | n before |
|---|
Part 3: Patterns & Examples
⚙️ Algorithms
Part 3 of 7 — Patterns & Examples
Common Algorithmic Patterns
You will see the same building blocks again and again. Recognize them and tracing becomes pattern-matching.
| Pattern | Shape |
|---|---|
| Accumulator | Start sum/product at identity, update each pass. |
| Counter | Increment when a condition holds. |
| Min/Max | Track best-so-far, compare each new element. |
| Filter | Build a new list of elements meeting a condition. |
| Map (transform) | Replace each element with f(element). |
Concept Check 🎯
Worked Example: Filter + Count
Goal: from prices, count how many are above 50 AND build a list of those prices.
prices ← [42, 73, 51, 18, 99, 50] count ← 0 expensive ← [] FOR EACH p IN prices { IF (p > 50) { count ← count + 1 APPEND(expensive, p) } }
Trace: 73 ✓, 51 ✓, 99 ✓. (50 fails because the test is strict >.) Output: 3 and [73, 51, 99].
Worked Example: Min Index, Not Just Min
Tracking the position of the minimum, not just the value.
Part 4: Connections & Interactions
⚙️ Algorithms
Part 4 of 7 — Connections & Interactions
How Algorithms Connect to Other CSP Topics
Algorithms don’t live in isolation. An efficient sort matters because of data size. A good search matters because the internet delivers gigabytes of records. The AP exam loves cross-topic questions.
| Connection | Why it matters |
|---|---|
| Algorithms ↔ Data | Choice of data structure (list vs. set) changes the algorithm’s running time. |
| Algorithms ↔ Abstraction | Procedures hide algorithmic detail behind a name. |
| Algorithms ↔ Computing Systems | Faster CPUs help, but a bad algorithm wastes any hardware budget. |
| Algorithms ↔ Impact | A biased ranking algorithm can amplify inequity at scale. |
Concept Check 🎯
Linear vs. Binary Search
| Algorithm | Requires | Time on n items |
|---|---|---|
| Linear | Nothing | up to n comparisons |
Part 5: Change Over Time
⚙️ Algorithms
Part 5 of 7 — Change Over Time
How Algorithms Scale
A "fast enough" algorithm at n = 100 may be unusable at n = 10,000,000. The AP exam tests whether you understand how running time grows with input size.
| Class | Doubling input multiplies time by | Practical feel |
|---|---|---|
| Constant | 1× | Instant regardless of size. |
| Logarithmic | adds a constant | Scales beautifully. |
| Linear | 2× | Reasonable. |
| Quadratic | 4× | Painful past ~10⁴. |
| Exponential | huge multiplier | Infeasible past tiny inputs. |
Concept Check 🎯
Reasonable vs. Unreasonable Algorithms
The CED uses two key terms:
- Reasonable: time grows polynomially (constant, log, linear, n², n³, …).
- Unreasonable: time grows exponentially (2ⁿ, n!, …) — quickly impossible to run.
A 30-element problem that needs to try every subset (2³⁰ ≈ 1 billion) is borderline. At 50 elements (2⁵⁰ ≈ 10¹⁵), no realistic computer finishes in your lifetime.
Part 6: Problem-Solving Workshop
⚙️ Algorithms
Part 6 of 7 — Problem-Solving Workshop
Algorithms Workshop
Walk through end-to-end problems that combine sequence, selection, iteration, lists, and procedures — exactly the style of CED FRQs.
Concept Check 🎯
Worked Problem: Average Skipping Zeros
PROCEDURE averageNonzero(scores) { total ← 0 count ← 0 FOR EACH s IN scores { IF (s ≠ 0) { total ← total + s; count ← count + 1 } } IF (count = 0) { RETURN 0 } RETURN total / count }
Test traces:
| Input | total | count | Result |
|---|---|---|---|
| [80, 0, 90, 100] | 270 | 3 | 90 |
| [0, 0] | 0 | 0 | 0 (guard) |
| [50] | 50 | 1 | 50 |
Worked Problem: Detecting a Pattern
Goal: return TRUE if a list contains two consecutive equal elements.
PROCEDURE hasRun(list) { FOR i ← 2 TO LENGTH(list) { IF (list[i] = list[i − 1]) { RETURN TRUE } } RETURN FALSE }
Why start at 2? list[i − 1] would be list[0] when i = 1, which doesn’t exist in 1-indexed pseudocode.
Part 7: AP Review
⚙️ Algorithms
Part 7 of 7 — AP Review
AP Exam Recap — Algorithms
Cheat sheet for exam day. Match each construct to its AP-pseudocode shape and the most common bug.
Concept Check 🎯
Quick-Reference: Constructs and Pitfalls
| Construct | Looks like | Common bug |
|---|---|---|
| Sequence | a; b; c | None — just trace top-down. |
| IF/ELSE | IF (c) {…} ELSE {…} | Wrong comparison (> vs ≥). |
| REPEAT N TIMES | block runs exactly N times | Modifying N inside changes nothing. |
| REPEAT UNTIL | runs at least once, exits when cond true | Forgetting it’s post-test (off by one). |
| FOR EACH x IN list | iterates over elements | Treating x as the index. |
| FOR i ← a TO b | iterates i = a, a+1, …, b | Off-by-one if pairing list[i+1]. |
Quick-Reference: Boolean Logic
- A AND B → both true.
- A OR B → at least one true.
- NOT (A AND B) = (NOT A) OR (NOT B) (DeMorgan).
- NOT (A OR B) = (NOT A) AND (NOT B).