Week 3: Algorithms
Algorithms: Searching, Sorting, and Complexity
This week focuses entirely on algorithms — how to implement them correctly, efficiently, and with good design. The discussion builds on the divide-and-conquer intuition from Week 0, applies it to arrays and memory, and develops a rigorous way to compare algorithm performance.
Searching Algorithms
Searching is a fundamental computational problem. Given an array of values stored contiguously in memory, the goal is to determine whether a particular value exists in that array. The array is a block of memory divided into equal-sized cells, each storing one value. The computer can only examine one cell at a time — like opening a closed door to see what is behind it.
Linear Search
Linear search works by checking every element from left to right (or right to left) until the target is found or the end of the array is reached.
Pseudocode (correct):
for each door from left to right
if 50 is behind the door
return true
return falseThe return false must be outside the loop; otherwise, the program would incorrectly return false after checking the first element. This is a common off-by-one or control flow bug.
Running time: In the worst case, every element must be checked. If there are n elements, up to n comparisons are needed. This is described as on the order of n steps.
Binary Search
Binary search works only on a sorted array. It repeatedly divides the search interval in half by comparing the target to the middle element and eliminating the half that cannot contain the target.
Pseudocode:
if no doors left
return false
if 50 is behind doors[middle]
return true
else if 50 < doors[middle]
search doors[0] through doors[middle-1]
else if 50 > doors[middle]
search doors[middle+1] through doors[n-1]The array is zero-indexed: the first element is at index 0, the last at index n-1. This makes middle-1 and middle+1 precise ways to shrink the search space.
Running time: Each comparison eliminates half of the remaining elements. If you start with n elements, the number of steps is at most log2n (in the worst case). This is fundamentally faster than linear search.
Key insight: Binary search requires sorted data. On unsorted data, binary search fails because the comparison with the middle element gives no reliable information about which half to discard.
Asymptotic Notation
To compare algorithms independently of hardware or implementation details, computer scientists use asymptotic notation — symbols that describe how an algorithm's running time grows as the input size n becomes large.
Big O (Upper Bound)
Big O notation describes the worst-case running time, or an upper bound on the number of steps. It ignores constant factors and lower-order terms.
Common big O complexities (from fastest to slowest):
O(1) — constant time (e.g., accessing a single array element)
O(logn) — logarithmic time (e.g., binary search)
O(n) — linear time (e.g., linear search)
O(nlogn) — linearithmic time (e.g., merge sort)
O(n2) — quadratic time (e.g., bubble sort, selection sort)
Linear search: O(n) — in the worst case, all n doors must be opened.
Binary search: O(logn) — each step halves the problem size.
Big Omega (Lower Bound)
Big Omega notation describes the best-case running time, or an lower bound.
Linear search best case: Ω(1) — the target could be behind the first door.
Binary search best case: Ω(1) — the target could be at the middle door.
Big Theta (Tight Bound)
When the upper bound and lower bound are the same function, we say the algorithm is in Θ of that function. For example, if an algorithm always takes Θ(n2) steps (regardless of input), we say it is Θ(n2).
Implementing Searching in C
Linear Search for Integers
#include <cs50.h>
#include <stdio.h>
int main(void)
{
int numbers[] = {20, 500, 10, 5, 100, 1, 50}; // array of 7 elements
int n = get_int("Number: "); // what to search for
for (int i = 0; i < 7; i++) // iterate through array
{
if (numbers[i] == n) // compare integers directly
{
printf("Found\n");
return 0; // success, exit program
}
}
printf("Not found\n");
return 1; // failure
}Key details:
return 0signals success; any non-zero value signals an error.If the
elsewere inside the loop, the program would incorrectly print "Not found" after checking the first element — a common control flow mistake.An uninitialized array contains garbage values — remnants of previous data in memory. Never rely on them.
Comparing Strings — The strcmp Function
Strings cannot be compared with == because that compares memory addresses, not the actual characters. The strcmp function from string.h compares strings character by character.
strcmp(s1, s2) return values:
0 if the strings are identical
< 0 if
s1comes befores2(ASCII-betically)> 0 if
s1comes afters2
#include <cs50.h>
#include <stdio.h>
#include <string.h> // needed for strcmp
int main(void)
{
string strings[] = {"battleship", "boot", "cannon", "iron", "thimble", "top hat"};
string s = get_string("String: ");
for (int i = 0; i < 6; i++)
{
if (strcmp(strings[i], s) == 0) // compare strings properly
{
printf("Found\n");
return 0;
}
}
printf("Not found\n");
return 1;
}Parallel Arrays and Their Problems
A simple phonebook can use two parallel arrays — one for names, one for numbers — relying on the same index to link a name to its number.
string names[] = {"David", "John", "Yuliia"};
string numbers[] = {"+1-617-495-1000", "+1-949-468-2750", "+1-617-495-1000"};Problems with this approach:
Magic numbers — hardcoding array sizes (e.g.,
3).Fragile alignment — if one array is updated without the other, data becomes mismatched.
Custom Data Types — struct
A better solution is to define a structure that bundles related data into a single type.
typedef struct
{
string name;
string number;
}
person;This creates a new type called person, which can be used just like int or string. An array of person keeps each entry's name and number together.
person people[3];
people[0].name = "David";
people[0].number = "+1-617-495-1000";
people[1].name = "John";
people[1].number = "+1-949-468-2750";
people[2].name = "Yuliia";
people[2].number = "+1-617-495-1000";The dot operator (.) accesses a member of the struct. Searching now compares the name field and returns the corresponding number field.
string name = get_string("Name: ");
for (int i = 0; i < 3; i++)
{
if (strcmp(people[i].name, name) == 0)
{
printf("Found %s\n", people[i].number);
return 0;
}
}
printf("Not found\n");
return 1;Why store phone numbers as strings? Numbers like phone numbers contain hyphens, plus signs, and parentheses; performing arithmetic on them makes no sense. A good rule of thumb: if you will never do math on a value, store it as a string.
Sorting Algorithms
Often it is worth sorting data once so that many subsequent searches can be fast. The trade-off is the time spent sorting vs. the time saved on repeated searches.
Selection Sort
Selection sort repeatedly finds the smallest element from the unsorted portion and swaps it into its correct position.
Pseudocode:
for i from 0 to n-1
find smallest element between numbers[i] and numbers[n-1]
swap smallest with numbers[i]How it works (example with 8 elements):
Scan all 8 elements, find the smallest (0), swap it with the element at index 0.
Scan the remaining 7 elements, find the smallest (1), swap with index 1.
Continue until one element remains — it is already in place.
Number of comparisons:
First pass: n-1 comparisons
Second pass: n-2 comparisons
… last pass: 1 comparison
Total = (n−1)+(n−2)+...+1=2n(n−1)
This expands to 2n2−2n. Using asymptotic notation, the highest-order term is n2. Therefore, selection sort is O(n2) and, because the algorithm always does the same number of comparisons regardless of input order, it is also Ω(n2) — making it Θ(n2).
Bubble Sort
Bubble sort repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order. Larger elements "bubble" to the end.
Pseudocode (unoptimized):
repeat n times
for i from 0 to n-2
if numbers[i] and numbers[i+1] are out of order
swap themOptimized version:
repeat until no swaps
for i from 0 to n-2
if numbers[i] and numbers[i+1] are out of order
swap them
if no swaps, quitHow it works (example with 8 elements):
Compare pairs (0 & 1, 1 & 2, …, 6 & 7), swapping when needed. The largest element ends up at the end.
Repeat, but note that the last element is already in place — we only need to go up to n-2, then n-3, etc.
Continue until a full pass produces no swaps.
Number of comparisons (unoptimized):
Outer loop runs n-1 times
Inner loop runs n-1 times each time
Total ≈ (n−1)(n−1)=n2−2n+1, i.e., O(n2)
Lower bound (optimized): If the array is already sorted, one pass (n-1 comparisons) confirms no swaps, so best case is Ω(n). The unoptimized version does not check for early termination and thus remains Ω(n2).
Visual comparison: Selection sort touches elements many times scanning for the minimum. Bubble sort also touches elements repeatedly, though the pattern is different. Both are O(n2) and slow on large data.
Recursion
A recursive algorithm is one that calls itself on a smaller version of the same problem. Every recursive function must have:
Base case(s) — the simplest instance that can be solved directly without recursion.
Recursive case(s) — the problem is broken into smaller pieces and the function calls itself.
Recursive Binary Search
Looking back at binary search, the pseudocode can be written recursively:
if no doors left
return false
if 50 is behind doors[middle]
return true
else if 50 < doors[middle]
search left half // recursive call
else
search right half // recursive callThe base case is "no doors left" — the search space has been exhausted. The recursive cases shrink the problem by half each time.
Recursive Pyramid Drawing
A pyramid of height n is a pyramid of height n-1 plus one more row of n bricks.
Base case: height 0 → do nothing.
Recursive implementation:
void draw(int n)
{
if (n == 0)
return;
draw(n - 1); // recursively draw the smaller pyramid
for (int i = 0; i < n; i++) // then draw the bottom row
printf("#");
printf("\n");
}Calling draw(4) results in:
draw(3)→draw(2)→draw(1)→draw(0)(base case, returns)Then prints 1
#, returnsThen prints 2
##, returnsThen prints 3
###, returnsThen prints 4
####, returns
The recursion "unwinds" — the smallest problem is solved first, then each larger problem builds on that result.
Merge Sort
Merge sort is a recursive sorting algorithm that achieves O(nlogn) running time — much faster than O(n2) for large n.
The algorithm (three lines):
sort left half of array
sort right half of array
merge the two sorted halvesBase case: if the array has 0 or 1 elements, it is already sorted — do nothing.
The Merge Step
Merging two already-sorted lists into one sorted list:
Point to the first element of each half.
Compare the two elements; place the smaller into a new array.
Advance the pointer from which you took the element.
Repeat until one half is empty, then copy the remaining elements.
Merging two halves each of size n/2 takes n comparisons (one per element). This is O(n).
Full Example (sorting 8 elements)
Starting array: [6, 3, 4, 1, 5, 2, 7, 0]
Divide phase (recursively split into halves):
Split into
[6,3,4,1]and[5,2,7,0]Split left half into
[6,3]and[4,1]Split
[6,3]into[6]and[3]— base cases reached.Continue splitting all the way down to single elements.
Conquer (merge) phase:
Merge
[6]and[3]→[3,6]Merge
[4]and[1]→[1,4]Merge
[3,6]and[1,4]→[1,3,4,6](left half sorted)Similarly, the right half becomes
[0,2,5,7]Finally, merge the two full halves:
[1,3,4,6]and[0,2,5,7]→[0,1,2,3,4,5,6,7]
Visual structure: The process can be drawn as a tree. There are log2n levels (layers of splitting), and at each level, merging all elements takes n steps. Total work: n⋅log2n operations.
Complexity of Merge Sort
Worst case (big O): O(nlogn) — this is true for every input because the algorithm always splits and merges regardless of initial order.
Best case (big Omega): Ω(nlogn) — even if already sorted, the algorithm still performs all the splitting and merging. (An optimization could check for a sorted list first, but the standard implementation does not.)
Therefore, merge sort is Θ(nlogn).
Space Trade-off
Merge sort requires extra memory — typically as much space as the original array — to hold the merged result during the merging step. This is a fundamental trade-off: faster running time often comes at the cost of more memory usage (space). Selection sort and bubble sort sort in place (using only a constant amount of extra space), but they are slower.
Comparing the Sorting Algorithms
Algorithm | Worst-case time | Best-case time | Extra space | Stable? |
|---|---|---|---|---|
Selection sort | O(n2) | Ω(n2) (always same) | O(1) (in place) | No (typical) |
Bubble sort (unoptimized) | O(n2) | Ω(n2) | O(1) (in place) | Yes |
Bubble sort (optimized) | O(n2) | Ω(n) (already sorted) | O(1) (in place) | Yes |
Merge sort | O(nlogn) | Ω(nlogn) | O(n) (extra array) | Yes |
Why this matters: For large n (millions of records), O(n2) is unusably slow, while O(nlogn) is practical. Libraries like C's qsort implement efficient sorting algorithms (often merge sort or quicksort) so that programmers don't have to write their own.
Key Takeaways
Linear search is simple, works on unsorted data, but is O(n).
Binary search is fast (O(logn)) but requires sorted data.
Sorting enables fast searching, but the upfront cost must be justified by many subsequent searches.
Asymptotic notation (big O, big Omega, big Theta) lets us compare algorithm efficiency independent of hardware.
Structures (
struct) group related data into a single type, improving code organization and reducing errors.Recursion is a technique where a function calls itself on a smaller problem, with a clear base case to stop.
Merge sort achieves O(nlogn) time by recursively splitting and merging, trading extra space for speed.
Algorithm design involves trade-offs between time, space, and development effort.

Ask anything
We've read this whole study set, so questions about it get the best answers.