O(log n) Algorithms
suggest changeLet’s say we have a problem of size n. At each step of the algorithm, the problem becomes half its previous size (n/2).
| Step | Problem size |
|---|---|
| 1 | n/2 |
| 2 | n/4 |
| 3 | n/8 |
| 4 | n/16 |
Once the problem size is 1, it cannot be reduced any further.
- At the kth step, the problem size is 1:
problem size = 1
- At that same step, the size is also:
problem size = n/2^k
-
From 1 and 2,
n/2^k = 1, son = 2^k. -
Take the logarithm of both sides:
ln n = k ln 2, sok = ln n / ln 2. -
By the change-of-base formula,
log_b(m) / log_b(c) = log_c(m), sok = log2(n), or simplyk = log n.
The algorithm therefore runs for at most log n steps, and its time complexity is O(log n).
A very simple example in code to support the text above is:
for (size_t i = 1; i <= n / 2; i *= 2) {
// perform some operation
}
If someone asks how many steps that loop runs when n is 256 (or how many steps any algorithm takes when it cuts the problem size in half), you can calculate it directly.
k = log2(256)
k = log2(2^8) (because log_a(a) = 1, so log2(2^8) = 8)
k = 8
Another very good example for similar case is Binary Search Algorithm.
int binary_search(const int values[], int length, int target) {
int low = 0;
int high = length - 1;
while (low <= high) {
const int middle = low + (high - low) / 2;
if (values[middle] == target) return middle;
if (values[middle] < target) low = middle + 1;
else high = middle - 1;
}
return -1;
}