Merge Sort
This chapter covers merge sort, the first sort we write that runs in . We write the merge of two sorted arrays, and then merge sort twice: bottom-up with loops, and top-down with recursion.
After reading this chapter, you should be able to:
- Trace and implement the two-pointer merge of two sorted arrays
- Analyze the merge: time and auxiliary space on every input
- Explain why the in-place merge uses auxiliary space but takes time in the worst case
- Implement bottom-up merge sort with loops, for an array of any length
- Trace recursive merge sort: the splits on the way down, and the merges on the way up in depth-first order
- Implement merge sort recursively
- Analyze both versions of merge sort: time on every input and auxiliary space
- Classify merge sort next to the quadratic sorts by time complexity class, auxiliary space, sensitivity to input order, and stability
You can download the accompanying code for this chapter: starter and solution.
Sections
- Merge Two Sorted Hands
- Merge Two Sorted Arrays
- Implementing the Merge Process
- Complexity of the Merge Process
- In-Place Merge
- In-Place Merge: Analysis
- The Common Way to Merge
- Repeating the Merge Process
- Bottom-Up Merge Sort
- Merge Sort: Time and Space Complexity
- Merge Sort: Best and Worst Case
- Merge Sort for Any Length
- Counting Up and Counting Down
- A Top-Down Trace
- Merge Sort, Recursively
- Analyzing the Recursive Version
- Properties of Merge Sort