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)∈O(2n)
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: Θ(|left|+|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)={Θ(1)if n≤ca⋅T(nb)+D(n)+C(n)otherwise
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 2i tasks, each with runtime Θ(n2i),
and there are log(n) levels.
At level i there are 2i tasks, each with runtime Θ(n2i),
and there are log(n) levels.
∑log(n)i=0 ∑2ij=1 Θ(n2i)
log(n)∑i=02i∑j=1Θ(n2i)
log(n)∑i=0(2i+1−1)Θ(n2i)
log(n)∑i=02iΘ(n2i)
log(n)∑i=0Θ(n)
(log(n)−0+1)Θ(n)
Θ(nlog(n))+Θ(n)
Θ(nlog(n))
Now use induction to prove that there is a c,n0
such that T(n)≤c⋅nlog(n) for any n>n0
Base Case: T(1)≤c⋅1
c0≤c
True for any c>c0
Assume: T(n2)≤cn2log(n2)
Show: T(n)≤cnlog(n)
2⋅T(n2)+c1+c2n≤cnlog(n)
By the assumption and transitivity, showing the following inequality suffices:
2cn2log(n2)+c1+c2n≤cnlog(n)
cnlog(n)−cnlog(2)+c1+c2n≤cnlog(n)
c1+c2n≤cnlog(2)
c1nlog(2)+c2log(2)≤c
True for any n0≥c1log(2) and c>c2log(2)+1