Overview of Merge Sort
We'll cover the following...
Because we're using divide-and-conquer to sort, we need to decide what our subproblems are going to look like. The full problem is to sort an entire array. Let's say that a subproblem is to sort a subarray. In particular, we'll think of a subproblem as sorting the subarray starting at index p
and going through index r
. It will be convenient to have a notation for a subarray, so let's say that
Here's how merge sort uses divide-and-conquer:
Divide by finding the number
q
of the position midway betweenp
andr
. Do this step the same way we found the midpoint in binary search: addp
andr
, divide by, and round down. Conquer by recursively sorting the subarrays in each of the two subproblems created by the divide step. That is, recursively sort the subarray
and recursively sort the subarray . Combine by merging the two sorted subarrays back into the single sorted subarray
.
We need a base case. The base case is a subarray containing fewer than two elements, that is, when