Implementation and Analysis of Merge Sort
Merge sort works fundamentally by recursively dividing an unsorted set of elements into
single-element divisions and merging the divisions repeatedly until a
single set is reproduced. In the implementation presented here,
data
initially contains the unsorted set of
size
elements stored in a single block of
contiguous storage. Since merging is not performed in place,
mgsort allocates additional storage for the
merges. Before mgsort returns, the final merged
set is copied back into data
.
As we have seen, an important part of merge sort is the process
of merging two sorted sets into a single sorted one. This task is
performed by the function merge (see Example 12.5), which merges the sets
defined from position i
to
j
and from j
+ 1
to k
in data
into a single sorted one from i
to
k
.
Initially, ipos
and
jpos
point to the beginning of each sorted
set. Merging continues as long as there are still elements in at least
one of the sets. While this is true, we proceed as follows. If one set
has no elements remaining to be merged, we place all elements
remaining in the other set into the merged set. Otherwise, we look at
which set contains the next element that should be placed in the
merged set to keep it properly ordered, place that element in the
merged set, and increment ipos
or
jpos
to the next element depending on from
which set the element came (see Figure
12.4).
Now we look at how the recursion proceeds in
Get Mastering Algorithms with C now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.