Merging Arrays
Mergesort sorts arrays by relying on another more basic algorithm known as merging arrays, or simply merging, for short. In this context, to merge arrays means to take two arrays that are already sorted, copy all of their values into a third array, and end up with the third array also completely sorted. Let’s look at a basic example.
Let’s say we have the arrays [3, 4, 7, 8] and [1, 2, 5, 6]. Note that each array is already sorted. I can’t emphasize this enough: merging arrays only works if the arrays are already sorted.
The goal of merging is to take all of the values from both arrays and copy them into a third array, which will contain all the values in sorted order. The result of merging these two arrays will be: [1, 2, 3, ...
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