I took discrete math (in which I learned about master theorem, Big Theta/Omega/O) a while ago and I seem to have forgotten the difference between O(logn) and O(2^n) (not in the
The other answers are correct, but don't make it clear - where does the large difference between the Fibonacci algorithm and divide-and-conquer algorithms come from? Indeed, the shape of the recursion tree for both classes of functions is the same - it's a binary tree.
The trick to understand is actually very simple: consider the size of the recursion tree as a function of the input size n
.
Recall some basic facts about binary trees first:
n
is a binary tree is equal to the the number of non-leaf nodes plus one. The size of a binary tree is therefore 2n-1.h
for a perfect binary tree with n
leaves is equal to log(n)
, for a random binary tree: h = O(log(n))
, and for a degenerate binary tree h = n-1
.Intuitively:
For sorting an array of n
elements with a recursive algorithm, the recursion tree has n
leaves. It follows that the width of the tree is n
, the height of the tree is O(log(n))
on the average and O(n)
in the worst case.
For calculating a Fibonacci sequence element k
with the recursive algorithm, the recursion tree has k
levels (to see why, consider that fib(k)
calls fib(k-1)
, which calls fib(k-2)
, and so on). It follows that height of the tree is k
. To estimate a lower-bound on the width and number of nodes in the recursion tree, consider that since fib(k)
also calls fib(k-2)
, therefore there is a perfect binary tree of height k/2
as part of the recursion tree. If extracted, that perfect subtree would have 2k/2 leaf nodes. So the width of the recursion tree is at least O(2^{k/2})
or, equivalently, 2^O(k)
.
The crucial difference is that:
Therefore the number of nodes in the tree is O(n)
in the first case, but 2^O(n)
in the second. The Fibonacci tree is much larger compared to the input size.
You mention Master theorem; however, the theorem cannot be applied to analyze the complexity of Fibonacci because it only applies to algorithms where the input is actually divided at each level of recursion. Fibonacci does not divide the input; in fact, the functions at level i
produce almost twice as much input for the next level i+1
.