34A. Elementary Analysis of Algorithms


Analysis of algorithms

We will be looking at computational problems with the goal of finding efficient ways to solve them. That requires that we can compare two algorithms to determine which is better, which involves finding out just efficient each algorithm is.

Algorithm analysis is concerned with determining how much of a resource, such as time or memory, an algorithm uses as a function of some characteristic of the input to the algorithm, usually the size of the input.

It is customary practice to use variable n for the number of characters that it takes to write down the input to an algorithm. The time or memory is given as a function of n. For example, a particular algorithm might take time n2.


Big-O and Θ notation

Usually it is not worth determining the exact cost of running an algorithm. An approximation is all we need. In fact, we usually want to know how the cost depends on n as n grows, not what the exact cost is; it is enough to know that the cost is proportional to some function of n. For expressing that, we use O and Θ notation.

Let f(n) and g(n) be two functions that take an integer n and yield an integer or real number. f(n) and g(n) are mathematical functions, not C++ functions.

Definition. Say that f(n) is O(g(n)) if there are constants c and n0 so that, for all nn0, f(n) ≤ cg(n). That is, for all sufficiently large values of n, f(n) ≤ cg(n).


Definition. Say that f(n) is Θ(g(n)) if f(n) is O(g(n)) and g(n) is O(f(n)).

For example,

When comparing functions using O and Θ, polymomials depend only on their degree. If f(n) is a polynomial of degree d and g(n) is a polynomial of degree e, then


Exercises

  1. True or false: n2 is O(n3). Answer

  2. True or false: n3 is O(n2). Answer

  3. True or false: n3 + 2n2n is Θ(n3). Answer

  4. True or false: n3 + 2n2n is Θ(n5). Answer