Merge Sort

Merge sort runs in O(n log2 n) time in the worst case, which is much better than O(n2). The constant factors are not so good, so we do not use merge sort for small n. Also, this is not an in-place sorting algorithm: we have to make a copy of the entire array. Merge sort relies heavily on a linear-time merge function.

See Demo mergeSort.cpp

Because the merge function makes copies of subarrays, it does not operate in place.

Divide and Conquer

Merge sort uses the divide and conquer paradigm.

  1. Divide the problem into approximately equal-sized subproblems.
  2. Conquer by solving the subproblems recursively.
  3. Combine their solutions to solve the original problem.

For merge sort we want to sort the subarray A[p..r].

  1. Divide: Find q = midpoint of subarray.
  2. Conquer: Recurse on A[p..q] and A[q + 1..r].
  3. Combine: Merge the sorted subarrays to form sorted A[p..r].

See Demo mergeSort.cpp

Analysis

To analyze merge sort, we

Here is a picture of the tree for merge sort:

To Index Previous Next