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.
- Divide the problem into approximately equal-sized
subproblems.
- Conquer by solving the subproblems recursively.
- Combine their solutions to solve the original problem.
For merge sort we want to sort the subarray A[p..r].
- Divide: Find q = midpoint of subarray.
- Conquer: Recurse on A[p..q] and A[q + 1..r].
- Combine: Merge the sorted subarrays to form sorted A[p..r].
See Demo mergeSort.cpp
Analysis
To analyze merge sort, we
- Draw a tree of how long each recursive call takes.
- Count only the time spent in steps 1 & 3 at each level.
- The divide time is constant so therefore we ignore it.
- Merging k elements takes time ck, for some constant c.
Here is a picture of the tree for merge sort:
To Index
Previous
Next