3. Recursion

The Process

Example: Merge Sort

Merge sort from left to middle, merge sort from middle to right and then merge the results:

The base case is when the length of the array is 0 or 1.

Analysis

For T(n)T(n), the cost will be either the base case of Θ(1)\Theta(1), or the sum of:

{Θ(1)n=12T(n2)+Θ(n)n>1 \begin{cases} \Theta(1) & n = 1 \\ 2T(\frac{n}{2}) + \Theta(n) & n > 1 \end{cases}

At each level, the cost will be:

Θ(n)=2Θ(n2)=4Θ(n4)=Θ(n) \begin{aligned} \Theta(n) &= 2\Theta(\frac{n}{2}) \\ &= 4\Theta(\frac{n}{4}) \\ &\dots \\ &= \Theta(n) \end{aligned}

There are log2n\log_2{n} levels, so the total cost is nlog2nn\log_2n.