O(log n) Algorithms

suggest change

Let’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.

  1. At the kth step, the problem size is 1:

problem size = 1

  1. At that same step, the size is also:

problem size = n/2^k

  1. From 1 and 2, n/2^k = 1, so n = 2^k.

  2. Take the logarithm of both sides: ln n = k ln 2, so k = ln n / ln 2.

  3. By the change-of-base formula, log_b(m) / log_b(c) = log_c(m), so k = log2(n), or simply k = 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;
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents