Mergesort
With Mergesort, you can make sure that your array contains two sorted halves before it performs a single-array merge, thereby sorting the array.
First, we’ll look at the steps of the Mergesort algorithm, and then we’ll walk through an example. The recursion may seem intimidating at first, but I assure you that the diagrams will clarify everything.
Let’s do it!
Here are the steps:
-
Create two new arrays. One is a copy of the array’s left half, and the other is a copy of the array’s right half.
-
Recursively perform Mergesort on the left copy. (Indeed, we’re already in the middle of Mergesort right now; that’s recursion for you.) The base case is when the array we perform Mergesort on contains one element or fewer.
-
Recursively perform ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access