Merging, and what divide-and-conquer actually costs
Merge sort is worth learning for one reason that has nothing to do with sorting — the merge step is a place to compute things, and once you see that, counting inversions, merging k sorted streams, and the whole "split, solve, combine" family stop being separate tricks and become one recurrence you can read off the code.
What you'll be able to do
- Merge two sorted sequences in linear time, and merge into a shared array from the back when there is no room for a copy
- Read the recurrence off a divide-and-conquer function and evaluate it with the recursion-tree argument
- Count inversions during the merge, and explain why the count is available exactly at the moment an element is taken from the right half
- Merge k sorted sequences in O(n log k) by pairing, and say why sequential merging is O(nk)
- Decide whether divide-and-conquer is worth it by comparing the combine step against solving directly
Before this: complexity-honestly, sorting-and-comparators
The rest of this lesson is in the app
Merge sort is worth learning for one reason that has nothing to do with sorting — the merge step is a place to compute things, and once you see that, counting inversions, merging k sorted streams, and the whole "split, solve, combine" family stop being separate tricks and become one recurrence you can read off the code. This walkthrough runs about 26 minutes, with runnable code you can edit and re-run as you read.
Continue in ChannelPulseThe first module of every track is free to read on the web — see what's open in Coding & data structures.