|
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.
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 n ≥ n0, 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,
5n2 is O(n2).
(Choose c = 5 and n0 = 0.
Observe that 5n2
< cn2 for all n.)
n2 is O(5n2).
(Choose c = 1 and n0 = 0.
Observe that n2
< cn2 for all n.)
5n2 is Θ(n2) since
5n2 is O(n2) and
n2 is O(5n2).
3n2 + 2n + 10 is O(n2).
(Choose n0 = 10 and c = 5. For all n ≥ 10,
3n2 + 2n + 10 ≤ 5n2.)
3n2 is O(n2 + 2n + 10).
(What values of n0 and c will work?)
3n2 + 2n + 10 is Θ(n2) since
n2 is O(3n2 + 2n + 10) and
3n2 + 2n + 10 is O(n2).
2n is O(n2).
(Choose n0 = 2 and c = 1.
n2 grows much faster than 2n
as n increases. For example, if n = 8,
2n = 16 and n2 = 64.)
n2 is not O(2n).
Function g(n) = n2 grows much faster than
f(n) = 2n.
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
f(n) is O(g(n))
if d ≤ e.
f(n) is Θ(g(n))
if d = e.
True or false: n2 is O(n3). Answer
True or false: n3 is O(n2). Answer
True or false: n3 + 2n2 − n is Θ(n3). Answer
True or false: n3 + 2n2 − n is Θ(n5). Answer
|