Merge sort is a recursive, divide and conquer sort algorithm. The idea of merge sort is pretty simple:
-
Divide your list into two lists.
-
If the lists have zero or one elements, they're sorted.
-
Otherwise, sort each of those lists recursively with merge sort.
-
Once those lists are sorted, we merge them together in sorted order.
Assuming that you have two sorted lists, what does the merge operation look like? The solution is similar to the intuitive approach:
-
Create a new list for the merge.
-
Compare the first item of the two lists.
-
Take the smallest of the two items from the head of its list and add it to your new list.
-
If one of the lists is empty, use the item from the other list.
-
Repeat from #2 until both lists are empty.
This is where merge sort starts to seem magical: once we have our merge operation, we're basically done. Try it out with pencil and paper!