Reading history

Asymptotic Analysis: Comparing Algorithms by Growth

7 min read 3 views

Learn asymptotic analysis: why we count steps, not seconds, how to drop constants and small terms, and what O, Omega and Theta mean. With C.

Asymptotic analysis compares algorithms by how their work grows as the input gets bigger, not by how many seconds they take on one computer. It lets you say “binary search beats linear search on large lists” and be right on every machine, from a phone to a supercomputer.

In this lesson you will learn

  • Why timing a program in seconds is a poor way to compare algorithms
  • How to count steps and watch how they grow
  • Why we drop constants and smaller terms
  • What Big O, Big Omega and Big Theta each promise
  • The common growth rates and how fast each one climbs

Why Seconds Are the Wrong Measure

Suppose you time two programs and one finishes in 0.2 seconds while the other takes 0.5. That result depends on the processor, the compiler settings, other programs running at the same moment, and the size of the test input. Run the same test on a different laptop and the answer may flip.

Asymptotic analysis removes the machine from the question. Instead of seconds, we count basic steps (comparisons, additions, assignments) as a function of the input size n. Then we ask: as n grows very large, how fast does that count grow?

Counting Steps: Linear vs Binary Search

Linear search checks items one at a time. Binary search, on a sorted array, checks the middle item and throws away half the remaining items each time. Here is the number of checks each makes in the worst case (target not found).

#include <stdio.h>

/* Count the steps each search needs in the worst case (target missing). */
static long linear_steps(long n) { return n; }

static long binary_steps(long n) {
    long steps = 0, lo = 0, hi = n - 1;
    while (lo <= hi) {          /* target is bigger than everything: always go right */
        long mid = lo + (hi - lo) / 2;
        steps++;
        lo = mid + 1;
    }
    return steps;
}

int main(void) {
    long sizes[] = {10, 1000, 1000000, 1000000000};
    printf("%12s %16s %14s\n", "n", "linear search", "binary search");
    for (int i = 0; i < 4; i++)
        printf("%12ld %16ld %14ld\n", sizes[i], linear_steps(sizes[i]), binary_steps(sizes[i]));
    return 0;
}

Output

           n    linear search  binary search
          10               10              4
        1000             1000             10
     1000000          1000000             20
  1000000000       1000000000             30

For 10 items the difference hardly matters. For a billion items, linear search needs a billion checks while binary search needs 30. Even if linear search ran on a computer 1,000 times faster, it would still lose badly on large inputs. Growth rate beats raw speed.

Keep the Biggest Term, Drop the Rest

Real step counts are messy, such as f(n) = 3n² + 5n + 20. Asymptotic analysis keeps only the part that matters for large n. The program below shows how much of the total comes from the 3n² term.

#include <stdio.h>

/* f(n) = 3n^2 + 5n + 20. How much of the total comes from the n^2 term? */
int main(void) {
    long ns[] = {1, 10, 100, 1000, 100000};
    printf("%8s %18s %12s\n", "n", "f(n)", "3n^2 share");
    for (int i = 0; i < 5; i++) {
        long n = ns[i];
        long big = 3 * n * n;
        long f = big + 5 * n + 20;
        printf("%8ld %18ld %11.2f%%\n", n, f, 100.0 * big / f);
    }
    return 0;
}

Output

       n               f(n)   3n^2 share
       1                 28       10.71%
      10                370       81.08%
     100              30520       98.30%
    1000            3005020       99.83%
  100000        30000500020      100.00%

At n = 1 the n² term is a small part of the total. By n = 1,000 it is 99.8%, and the other terms no longer matter. So we keep n², and we also drop the constant 3, because a constant multiplier does not change the shape of the growth. We say f(n) is O(n²).

Two simple rules cover most cases:

  1. Keep only the fastest-growing term. n² + n → n²; n + log n → n.
  2. Drop constant multipliers. 5n → n; n/2 → n; 100 → 1.

The Three Notations: O, Ω and Θ

NotationRead asPromiseEveryday meaning
O(g(n))Big Of(n) grows no faster than g(n), for large nAn upper limit: “at most this much”
Ω(g(n))Big Omegaf(n) grows at least as fast as g(n)A lower limit: “at least this much”
Θ(g(n))Big ThetaBoth at once: f(n) grows exactly like g(n)A tight description: “about this much”

For f(n) = 3n² + 5n + 20, all of these are true: O(n²), O(n³), Ω(n²), Ω(n) and Θ(n²). The most useful is the tightest one, Θ(n²). In everyday speech, programmers often say “O(n²)” when they mean Θ(n²).

Each notation has its own detailed lesson: Big O, Omega and Theta.

Common Growth Rates Side by Side

This program prints how many steps the most common growth rates need for a few input sizes.

#include <stdio.h>
#include <math.h>

/* Operations needed by common growth rates, for a few input sizes. */
int main(void) {
    int ns[] = {10, 100, 1000, 10000};
    printf("%7s %9s %8s %12s %14s\n", "n", "log2 n", "n", "n log2 n", "n^2");
    for (int i = 0; i < 4; i++) {
        double n = ns[i];
        printf("%7d %9.1f %8.0f %12.0f %14.0f\n",
               ns[i], log2(n), n, n * log2(n), n * n);
    }
    return 0;
}

Output

      n    log2 n        n     n log2 n            n^2
     10       3.3       10           33            100
    100       6.6      100          664          10000
   1000      10.0     1000         9966        1000000
  10000      13.3    10000       132877      100000000
GrowthNameTypical example
O(1)ConstantReading arr[i]
O(log n)LogarithmicBinary search
O(n)LinearFinding the largest item
O(n log n)LinearithmicMerge sort, heap sort
O(n²)QuadraticChecking every pair, insertion sort
O(2n)ExponentialTrying every subset

A practical rule for programming contests and interviews: about 100 million simple steps run in roughly a second. So O(n²) is fine for n = 10,000 (100 million steps) but far too slow for n = 1,000,000.

What Asymptotic Analysis Does Not Tell You

  • Behaviour on small inputs. For n = 20, a simple O(n²) sort can beat a complex O(n log n) one, because the dropped constants matter. Many library sorts switch to insertion sort for small pieces for exactly this reason.
  • Memory effects. Two O(n) loops can differ several times in speed depending on how they use the CPU cache.
  • Which input you get. An algorithm can be fast on some inputs and slow on others. That is covered by best, average and worst case analysis.

Use asymptotic analysis to choose the right algorithm, then measure real code to tune it.

Common Mistakes

  1. Keeping constants. O(2n) and O(n/2) are both just O(n).
  2. Adding when you should multiply. Two loops one after another are O(n + n) = O(n). A loop inside another loop is O(n × n) = O(n²).
  3. Assuming every loop is O(n). A loop that doubles its counter (i *= 2) runs only about log₂n times.
  4. Ignoring hidden work. Calling strlen(s) inside a loop condition re-scans the string every time, turning an O(n) loop into O(n²).
  5. Treating O as “exact”. O is only an upper bound. Say Θ when you mean the growth is exactly that.

Practice Exercises

Exercise 1. Simplify each into Big O form: (a) 7n + 300, (b) n²/2 + 10n, (c) 4 log n + 9, (d) 2n + n³.

Show answer

(a) O(n), (b) O(n²), (c) O(log n), (d) O(2n).

Exercise 2. What is the growth rate of this code?

for (int i = 0; i < n; i++)
    for (int j = 1; j < n; j *= 2)
        count++;
Show answer

The outer loop runs n times and the inner loop about log₂n times, so the total is O(n log n).

Exercise 3. Algorithm A takes 100n steps. Algorithm B takes n² steps. For which values of n is A faster?

Show answer

A is faster when 100n < n², which means n > 100. For n below 100, B wins despite its worse growth rate.

Frequently Asked Questions

What does “asymptotic” mean?

It describes what happens as n becomes very large, approaching infinity. We care about the trend for big inputs, not the exact count for small ones.

Is Big O the worst case?

Not by definition. Big O is an upper bound on a function. It is most often used for the worst case, but you can give an O bound for any case.

Why is log n usually written without a base?

Logarithms in different bases differ only by a constant factor, and constants are dropped. So O(log₂n) and O(log₁₀n) are the same class.

Does a lower Big O always mean a faster program?

For large enough inputs, yes. For small inputs, constants and hardware effects can make the “slower” algorithm win.

Summary

  • Asymptotic analysis counts steps as a function of input size n, so results do not depend on the machine.
  • Keep the fastest-growing term and drop constant multipliers.
  • O is an upper bound, Ω a lower bound, Θ a tight bound.
  • Common rates from fastest to slowest: 1, log n, n, n log n, n², 2n.
  • Use it to choose algorithms; measure real code to fine-tune.
Lessons are also marked complete when you click Next.