Mergesort analysis [00PQ]

How long does mergesort take on a list of length n? Looking at the code above, we can see that

  • It takes \Theta (1) in the base case (a list of length \leq 1).
  • Otherwise, it makes two recursive calls to itself on lists of length approximately n/2.
  • After the recursive calls complete, it does \Theta (n) additional work to merge the two sorted lists into a single sorted list.
If we let T(n) denote the amount of time taken by mergesort on an input list of length n, we can thus write the following recurrence: \begin {align*} T(1) &= \Theta (1) \\ T(n) &= 2 T(n/2) + \Theta (n). \end {align*} Can we find a closed form for this recurrence?

If we draw out a tree showing all the recursive calls of \mathsf {mergesort} on an initial input of length n, it looks something like this:

The expression at each node indicates both the size of the input to that recursive call, as well as the amount of work which happens at that node (since the amount of work at each node is linear). We can see that
  • The tree has height \lg n, since we divide the input in half at each level until reaching a base case of 1.
  • There is n total work happening at each level: n = n/2 + n/2 = n/4 + n/4 + n/4 + n/4 = \dots .
Hence, the total amount of work done by mergesort overall is \Theta (n \lg n).