Where log n comes from
O(log n) is the cost of halving the range at every step: guessing a number from 1 to 100 takes at most 7 guesses, and binary search in a sorted array of a million needs only about 20 steps.
Guess a number from 1 to 100, and after each guess you are told "too high" or "too low". The smart way is to guess the middle every time: 50, then 25 or 75… and 7 guesses are always enough. 100 numbers, 7 steps: that is log n.
Halving every time
Each guess leaves half as many possibilities: 100 → 50 → 25 → 13 → 7 → 4 → 2 → 1. The number of halvings it takes to get from n down to 1 is log₂ n.
1#include <stdio.h>2 3int halvings(int n) {4 int steps = 0;5 while (n > 1) {6 n /= 2;7 steps++;8 }9 return steps;10}11 12int main(void) {13 int sizes[] = {8, 100, 1000, 1000000};14 for (int k = 0; k < 4; k++)15 printf("n = %7d %d halvings\n", sizes[k], halvings(sizes[k]));16 return 0;17}
n = 8 3 halvings n = 100 6 halvings n = 1000 9 halvings n = 1000000 19 halvings
n grows from 1000 to a million (1000 times), and the steps only from 9 to 19 (10 more). That is what makes O(log n) so good.
| n | log₂ n (about) |
|---|---|
| 1 000 | 10 |
| 1 000 000 | 20 |
| 1 000 000 000 | 30 |
i doubles each time. With n = 100, what does it print?
1#include <stdio.h>2 3int main(void) {4 int n = 100, steps = 0;5 for (int i = 1; i < n; i *= 2)6 steps++;7 printf("%d\n", steps);8 return 0;9}
An O(log n) algorithm takes about 10 steps for n = 1000. About how many does it take when n becomes 2000?
How many halvings down to 1
✓Finish the loop: divide n by 2 (integer division) until it is no longer above 1, and count the halvings for n = 1000.
9
1#include <stdio.h>2 3int main(void) {4 int n = 1000, steps = 0;5 // in a while: halve n, add 1 to steps6 printf("%d\n", steps);7 return 0;8}
Binary search
In an array that is already sorted you can search the same way: look at the middle; if it is smaller than what you want, search only the right half, and if it is bigger, only the left half.
lo↑hi↑mid1int lo = 0, hi = n - 1;2while (lo <= hi) {3 int mid = (lo + hi) / 2;4 if (a[mid] == x) return mid;5 if (a[mid] < x) lo = mid + 1;6 else hi = mid - 1;7}8return -1;
1#include <stdio.h>2 3int binary_search(int a[], int n, int x, int *steps) {4 int lo = 0, hi = n - 1;5 while (lo <= hi) {6 int mid = (lo + hi) / 2;7 (*steps)++;8 if (a[mid] == x) return mid;9 if (a[mid] < x) lo = mid + 1;10 else hi = mid - 1;11 }12 return -1;13}14 15int main(void) {16 int a[1000];17 for (int i = 0; i < 1000; i++)18 a[i] = 2 * i; // 0 2 4 … 1998, sorted19 int steps = 0;20 int at = binary_search(a, 1000, 1234, &steps);21 printf("1234 is at index %d, after %d looks\n", at, steps);22 return 0;23}
1234 is at index 617, after 10 looks
1000 numbers, at most 10 looks. Searching one by one could take 1000.
The catch: binary search only works on a sorted array. If it isn't sorted, the half you throw away may hold the number you want.
Often asked: binary search over n elements takes at most ⌊log₂ n⌋ + 1 comparisons to find an element (at most 4 for 10 elements).
Fill in the blank so that binary search finds 11 and prints its index, 5.
1#include <stdio.h>2 3int main(void) {4 int a[] = {1, 3, 5, 7, 9, 11, 13};5 int lo = 0, hi = 6, x = 11, at = -1;6 while (lo <= hi) {7 int mid = (lo + hi) / 2;8 if (a[mid] == x) { at = mid; break; }9 if (a[mid] < x) lo = ;10 else hi = mid - 1;11 }12 printf("%d\n", at);13 return 0;14}
a[mid] < x means mid and everything to its left is smaller than x, so the next try starts one place to the right of mid: lo = mid + 1. With lo = mid the range may never shrink and the loop may never stop; with mid - 1 you bring back places you've already ruled out.At most how many looks does binary search need on 1000 sorted numbers?
Write binary search
✓Finish binary_search: find x in the sorted array a and return its index, or -1 if it isn't there.
5 -1
1#include <stdio.h>2 3int binary_search(int a[], int n, int x) {4 int lo = 0, hi = n - 1;5 // while (lo <= hi): look at the middle, then drop a half6 return -1;7}8 9int main(void) {10 int a[] = {2, 5, 8, 12, 16, 23, 38, 56, 72, 91};11 printf("%d\n", binary_search(a, 10, 23));12 printf("%d\n", binary_search(a, 10, 7));13 return 0;14}
Spotting log n in code
To tell whether a loop is log n, look at how the loop variable changes each time:
- it adds or subtracts a number (
i++,i += 2,i--): the runs are proportional to n, so it is O(n); - it multiplies or divides by a number (
i *= 2,n /= 2,i *= 3): it is done in a few steps, so it is O(log n).
for (i = 0; i < n; i += 2)512 timesO(n): just half as manyfor (i = 1; i < n; i *= 2)10 timesO(log n)Put one inside the other: the outer loop runs n times and the inner one doubles each time, n × log n steps in all, written O(n log n). It's a bit slower than O(n) and far faster than O(n²); merge sort and heap sort, coming later, grow exactly like this.
1#include <stdio.h>2 3int main(void) {4 int sizes[] = {8, 64, 1024};5 for (int k = 0; k < 3; k++) {6 int n = sizes[k], steps = 0;7 for (int i = 0; i < n; i++)8 for (int j = 1; j < n; j *= 2)9 steps++;10 printf("n = %4d %d steps\n", n, steps);11 }12 return 0;13}
n = 8 24 steps n = 64 384 steps n = 1024 10240 steps
For n = 1024 that's 10240 steps; if both loops ran all n times, it would be 1024 × 1024, just over a million.
Which piece of code is O(log n)?
The outer loop runs n times; the inner one doubles each time. What does it print?
1#include <stdio.h>2 3int main(void) {4 int n = 32, steps = 0;5 for (int i = 0; i < n; i++)6 for (int j = 1; j < n; j *= 2)7 steps++;8 printf("%d\n", steps);9 return 0;10}
Summary
Halving every step is O(log n)
- For n = a million, log₂ n is only about 20
- Doubling each time and halving each time are both log n
- Binary search only works on a sorted array
- n outer runs with an inner loop that doubles: O(n log n)
1while (lo <= hi) {2 mid = (lo + hi) / 2;3 if (a[mid] == x) return mid;4 if (a[mid] < x) lo = mid + 1;5 else hi = mid - 1;6}
Chapter 0 quick check
4 questions. Work out what each prints before you pick; they are the forms these come up in most, in exams and interviews.
The inner loop only goes up to i. What does it print for n = 5?
1#include <stdio.h>2 3int main(void) {4 int n = 5, steps = 0;5 for (int i = 0; i < n; i++)6 for (int j = 0; j < i; j++)7 steps++;8 printf("%d\n", steps);9 return 0;10}
i is multiplied by 3 each time. What does it print?
1#include <stdio.h>2 3int main(void) {4 int n = 100, steps = 0;5 for (int i = 1; i < n; i *= 3)6 steps++;7 printf("%d\n", steps);8 return 0;9}
What does it print, and what is its complexity?
1#include <stdio.h>2 3int main(void) {4 int n = 10, steps = 0;5 for (int i = 0; i < n; i++)6 for (int j = 0; j < 3; j++)7 steps++;8 for (int k = 0; k < n; k++)9 steps++;10 printf("%d\n", steps);11 return 0;12}
Binary search for 22 in 0, 2, 4, …, 30. How many looks?
1#include <stdio.h>2 3int main(void) {4 int a[16];5 for (int i = 0; i < 16; i++)6 a[i] = i * 2;7 int lo = 0, hi = 15, x = 22, looks = 0;8 while (lo <= hi) {9 int mid = (lo + hi) / 2;10 looks++;11 if (a[mid] == x) break;12 if (a[mid] < x) lo = mid + 1;13 else hi = mid - 1;14 }15 printf("%d\n", looks);16 return 0;17}