Sept 26, 2022
Warm up...
What's the complexity? (in terms of n)
def fibb(n: Int): Long =
if(n < 2){ 1 }
else { fibb(n-1) + fibb(n-2) }
Test Hypothesis: $T(n) \in O(2^n)$
Remember the Towers of Hanoi...
...
To solve the problem at $n$:
Input: An array with elements in unknown order.
Output: An array with elements in sorted order.
Observation: Merging two sorted arrays can be done in $O(n)$.
def merge[A: Ordering](left: Seq[A], right: Seq[A]): Seq[A] = {
val output = ArrayBuffer[A]()
val leftItems = left.iterator.buffered
val rightItems = right.iterator.buffered
while(leftItems.hasNext || rightItems.hasNext) {
if(!left.hasNext) { output.append(right.next) }
else if(!right.hasNext) { output.append(left.next) }
else if(Ordering[A].lt( left.head, right.head ))
{ output.append(left.next) }
else { output.append(right.next) }
}
output.toSeq
}
Each time though loop advances either left or right.
Total Runtime: $\Theta(|\texttt{left}| + |\texttt{right}|)$
Observation: Merging two sorted arrays can be done in $O(n)$.
Idea: Split the input in half, sort each half, and merge.
To solve the problem at $n$:
def sort[A: Ordering](data: Seq[A]): Seq[A] =
{
if(data.length <= 1) { return data }
else {
val (left, right) = data.splitAt(data.length / 2)
return merge(
sort(left),
sort(right)
)
}
}
If we solve a problem of size $n$ by:
The total cost will be: $$T(n) = \begin{cases} \Theta(1) & \textbf{if } n \leq c \\ a\cdot T(\frac{n}{b}) + D(n) + C(n) & \textbf{otherwise} \end{cases}$$
How can we find a closed-form hypothesis?
Idea: Draw out the cost of each level of recursion.
Each node of the tree shows $D(n) + C(n)$
At level $i$ there are $2^i$ tasks, each with runtime $\Theta(\frac{n}{2^i})$,
and there are $\log(n)$ levels.
At level $i$ there are $2^i$ tasks, each with runtime $\Theta(\frac{n}{2^i})$,
and there are $\log(n)$ levels.
$\sum_{i=0}^{\log(n)}$ $\sum_{j=1}^{2^i}$ $\Theta(\frac{n}{2^i})$
$$\sum_{i=0}^{\log(n)} \sum_{j=1}^{2^i} \Theta(\frac{n}{2^i})$$
$$\sum_{i=0}^{\log(n)} (2^i+1-1)\Theta(\frac{n}{2^i})$$
$$\sum_{i=0}^{\log(n)} 2^i\Theta(\frac{n}{2^i})$$
$$\sum_{i=0}^{\log(n)} \Theta(n)$$
$$(\log(n) - 0 + 1) \Theta(n)$$
$$\Theta(n\log(n)) + \Theta(n)$$
$$\Theta(n\log(n))$$
Now use induction to prove that there is a $c, n_0$
such that $T(n) \leq c \cdot n\log(n)$ for any $n > n_0$
Base Case: $T(1) \leq c \cdot 1$
$$c_0 \leq c$$
True for any $c > c_0$
Assume: $T(\frac{n}{2}) \leq c \frac{n}{2} \log\left(\frac{n}{2}\right)$
Show: $T(n) \leq c n \log\left(n\right)$
$$2\cdot T(\frac{n}{2}) + c_1 + c_2 n \leq c n \log(n)$$
By the assumption and transitivity, showing the following inequality suffices:
$$2 c \frac{n}{2} \log\left(\frac{n}{2}\right) + c_1 + c_2 n \leq c n \log(n)$$
$$c n \log(n) - c n \log(2) + c_1 + c_2 n \leq c n \log(n)$$
$$c_1 + c_2 n \leq c n \log(2)$$
$$\frac{c_1}{n \log(2)} + \frac{c_2}{\log(2)} \leq c$$
True for any $n_0 \geq \frac{c_1}{\log(2)}$ and $c > \frac{c_2}{\log(2)}+1$