Search⌘ K
AI Features

Analysis of Merge Sort

Understand the analysis of merge sort by exploring its divide-and-conquer approach that divides arrays, recursively sorts subarrays, and merges them. Learn why merge sort runs in Theta n log n time and how it compares to in-place algorithms in terms of space usage.

We'll cover the following...

Given that the merge function runs in Θ(n)\Theta(n) time when merging nn elements, how do we get to showing that mergeSort() runs in Θ(nlogn)\Theta(n \log n) time? We start by thinking about the three parts of divide-and-conquer and how to account for their running times. We assume that we're sorting a total of nn elements in the entire array.

The divide step takes constant time, regardless of the subarray size. After all, the divide step just computes the midpoint qq of the indices pp and rr. Recall that in big–Θ\Theta notation, we indicate constant time by Θ(1)\Theta(1).

The conquer step, where we recursively sort two subarrays of approximately n/2n/2 elements each, takes some amount of time, but we'll account for that time when we consider the subproblems.

The combine step merges a total of nn elements, taking Θ(n)\Theta(n) time.

If we think about the divide and combine steps together, the Θ(1)\Theta(1) running time for the divide step is a low-order term when compared with the Θ(n)\Theta(n) running time of the combine step. So let's think of the divide and combine steps together as taking Θ(n)\Theta(n) time. To make things more concrete, let's ...