Merge sort


In computer science, merge sort is an efficient, general-purpose, comparison-based sorting algorithm. Most implementations produce a stable sort, which means that the order of equal elements is the same in the input and output. Merge sort is a divide and conquer algorithm that was invented by John von Neumann in 1945. A detailed description and analysis of bottom-up mergesort appeared in a report by Goldstine and von Neumann as early as 1948.

Algorithm

Conceptually, a merge sort works as follows:
  1. Divide the unsorted list into n sublists, each containing one element.
  2. Repeatedly merge sublists to produce new sorted sublists until there is only one sublist remaining. This will be the sorted list.

    Top-down implementation

Example C-like code using indices for top-down merge sort algorithm that recursively splits the list into sublists until sublist size is 1, then merges those sublists to produce a sorted list. The copy back step is avoided with alternating the direction of the merge with each level of recursion. To help understand this, consider an array with 2 elements. The elements are copied to B, then merged back to A. If there are 4 elements, when the bottom of recursion level is reached, single element runs from A are merged to B, and then at the next higher level of recursion, those 2 element runs are merged to A. This pattern continues with each level of recursion.

// Array A has the items to sort; array B is a work array.
void TopDownMergeSort
// Sort the given run of array A using array B as a source.
// iBegin is inclusive; iEnd is exclusive.
void TopDownSplitMerge
// Left source half is A.
// Right source half is A.
// Result is B.
void TopDownMerge
void CopyArray

Sorting the entire array is accomplished by.

[|Bottom-up implementation]

Example C-like code using indices for bottom-up merge sort algorithm which treats the list as an array of n sublists of size 1, and iteratively merges sub-lists back and forth between two buffers:

// array A has the items to sort; array B is a work array
void BottomUpMergeSort
// Left run is A.
// Right run is A.
void BottomUpMerge
void CopyArray

Top-down implementation using lists

for top-down merge sort algorithm which recursively divides the input list into smaller sublists until the sublists are trivially sorted, and then merges the sublists while returning up the call chain.
function merge_sort is
// Base case. A list of zero or one elements is sorted, by definition.
if length of m ≤ 1 then
return m
// Recursive case. First, divide the list into equal-sized sublists
// consisting of the first half and second half of the list.
// This assumes lists start at index 0.
var left := empty list
var right := empty list
for each x with index i in m do
if i < /2 then
add x to left
else
add x to right
// Recursively sort both sublists.
left := merge_sort
right := merge_sort
// Then merge the now-sorted sublists.
return merge
In this example, the function merges the left and right sublists.
function merge is
var result := empty list
while left is not empty and right is not empty do
if first ≤ first then
append first to result
left := rest
else
append first to result
right := rest
// Either left or right may have elements left; consume them.
// '
while left is not empty do
append first to result
left := rest
while right is not empty do
append first to result
right := rest
return''' result

Bottom-up implementation using lists

for bottom-up merge sort algorithm which uses a small fixed size array of references to nodes, where array is either a reference to a list of size 2i or nil. node is a reference or pointer to a node. The merge function would be similar to the one shown in the top-down merge lists example, it merges two already sorted lists, and handles empty lists. In this case, merge would use node for its input parameters and return value.
function merge_sort is
// return if empty list
if head = nil then
return nil
var node array; initially all nil
var node result
var node next
var int i
result := head
// merge nodes into array
while result ≠ nil do
next := result.next;
result.next := nil
for && do
result := merge
array := nil
// do not go past end of array
if i = 32 then
i -= 1
array := result
result := next
// merge array into single list
result := nil
for do
result := merge
return result

Natural merge sort

A natural merge sort is similar to a bottom-up merge sort except that any naturally occurring runs in the input are exploited. Both monotonic and bitonic runs may be exploited, with lists being convenient data structures. In the bottom-up merge sort, the starting point assumes each run is one item long. In practice, random input data will have many short runs that just happen to be sorted. In the typical case, the natural merge sort may not need as many passes because there are fewer runs to merge. In the best case, the input is already sorted, so the natural merge sort need only make one pass through the data. In many practical cases, long natural runs are present, and for that reason natural merge sort is exploited as the key component of Timsort. Example:
Start : 3 4 2 1 7 5 8 9 0 6
Select runs :
Merge :
Merge :
Merge :
Tournament replacement selection sorts are used to gather the initial runs for external sorting algorithms.

Analysis

In sorting n objects, merge sort has an average and worst-case performance of O. If the running time of merge sort for a list of length n is T, then the recurrence T = 2T + n follows from the definition of the algorithm. The closed form follows from the master theorem for divide-and-conquer recurrences.
In the worst case, the number of comparisons merge sort makes is given by the sorting numbers. These numbers are equal to or slightly smaller than, which is between and.
For large n and a randomly ordered input list, merge sort's expected number of comparisons approaches α·n fewer than the worst case where
In the worst case, merge sort does about 39% fewer comparisons than quicksort does in the average case. In terms of moves, merge sort's worst case complexity is O—the same complexity as quicksort's best case, and merge sort's best case takes about half as many iterations as the worst case.
Merge sort is more efficient than quicksort for some types of lists if the data to be sorted can only be efficiently accessed sequentially, and is thus popular in languages such as Lisp, where sequentially accessed data structures are very common. Unlike some implementations of quicksort, merge sort is a stable sort.
Merge sort's most common implementation does not sort in place; therefore, the memory size of the input must be allocated for the sorted output to be stored in.

Variants

Variants of merge sort are primarily concerned with reducing the space complexity and the cost of copying.
A simple alternative for reducing the space overhead to n/2 is to maintain left and right as a combined structure, copy only the left part of m into temporary space, and to direct the merge routine to place the merged output into m. With this version it is better to allocate the temporary space outside the merge routine, so that only one allocation is needed. The excessive copying mentioned previously is also mitigated, since the last pair of lines before the return result statement become superfluous.
One drawback of merge sort, when implemented on arrays, is its working memory requirement. Several in-place variants have been suggested:
An alternative to reduce the copying into multiple lists is to associate a new field of information with each key. This field will be used to link the keys and any associated information together in a sorted list. Then the merging of the sorted lists proceeds by changing the link values; no records need to be moved at all. A field which contains only a link will generally be smaller than an entire record so less space will also be used. This is a standard sorting technique, not restricted to merge sort.

Use with tape drives

An external merge sort is practical to run using disk or tape drives when the data to be sorted is too large to fit into memory. External sorting explains how merge sort is implemented with disk drives. A typical tape drive sort uses four tape drives. All I/O is sequential. A minimal implementation can get by with just two record buffers and a few program variables.
Naming the four tape drives as A, B, C, D, with the original data on A, and using only 2 record buffers, the algorithm is similar to Bottom-up implementation, using pairs of tape drives instead of arrays in memory. The basic algorithm can be described as follows:
  1. Merge pairs of records from A; writing two-record sublists alternately to C and D.
  2. Merge two-record sublists from C and D into four-record sublists; writing these alternately to A and B.
  3. Merge four-record sublists from A and B into eight-record sublists; writing these alternately to C and D
  4. Repeat until you have one list containing all the data, sorted—in log2 passes.
Instead of starting with very short runs, usually a hybrid algorithm is used, where the initial pass will read many records into memory, do an internal sort to create a long run, and then distribute those long runs onto the output set. The step avoids many early passes. For example, an internal sort of 1024 records will save nine passes. The internal sort is often large because it has such a benefit. In fact, there are techniques that can make the initial runs longer than the available internal memory.
With some overhead, the above algorithm can be modified to use three tapes. O running time can also be achieved using two queues, or a stack and a queue, or three stacks. In the other direction, using k > two tapes, we can reduce the number of tape operations in O times by using a k/2-way merge.
A more sophisticated merge sort that optimizes tape drive usage is the polyphase merge sort.

Optimizing merge sort

On modern computers, locality of reference can be of paramount importance in software optimization, because multilevel memory hierarchies are used. Cache-aware versions of the merge sort algorithm, whose operations have been specifically chosen to minimize the movement of pages in and out of a machine's memory cache, have been proposed. For example, the algorithm stops partitioning subarrays when subarrays of size S are reached, where S is the number of data items fitting into a CPU's cache. Each of these subarrays is sorted with an in-place sorting algorithm such as insertion sort, to discourage memory swaps, and normal merge sort is then completed in the standard recursive fashion. This algorithm has demonstrated better performance on machines that benefit from cache optimization.
suggested an alternative version of merge sort that uses constant additional space. This algorithm was later refined.
Also, many applications of external sorting use a form of merge sorting where the input get split up to a higher number of sublists, ideally to a number for which merging them still makes the currently processed set of pages fit into main memory.

Parallel merge sort

Merge sort parallelizes well due to the use of the divide-and-conquer method. Several different parallel variants of the algorithm have been developed over the years. Some parallel merge sort algorithms are strongly related to the sequential top-down merge algorithm while others have a different general structure and use the K-way merge method.

Merge sort with parallel recursion

The sequential merge sort procedure can be described in two phases, the divide phase and the merge phase. The first consists of many recursive calls that repeatedly perform the same division process until the subsequences are trivially sorted. An intuitive approach is the parallelization of those recursive calls. Following pseudocode describes the merge sort with parallel recursion using the fork and join keywords:
// Sort elements lo through hi of array A.
algorithm mergesort is
if lo+1 < hi then // Two or more elements.
mid := ⌊ / 2⌋
fork mergesort
mergesort
join
merge
This algorithm is the trivial modification of the sequential version and does not parallelize well. Therefore, its speedup is not very impressive. It has a span of, which is only an improvement of compared to the sequential version. This is mainly due to the sequential merge method, as it is the bottleneck of the parallel executions.

Merge sort with parallel merging

Better parallelism can be achieved by using a parallel merge algorithm. Cormen et al. present a binary variant that merges two sorted sub-sequences into one sorted output sequence.
In one of the sequences, the element of the middle index is selected. Its position in the other sequence is determined in such a way that this sequence would remain sorted if this element were inserted at this position. Thus, one knows how many other elements from both sequences are smaller and the position of the selected element in the output sequence can be calculated. For the partial sequences of the smaller and larger elements created in this way, the merge algorithm is again executed in parallel until the base case of the recursion is reached.
The following pseudocode shows the modified parallel merge sort method using the parallel merge algorithm.
/**
* A: Input array
* B: Output array
* lo: lower bound
* hi: upper bound
* off: offset
*/
algorithm parallelMergesort is
len := hi - lo + 1
if len 1 then
B := A
else let T be a new array
mid := ⌊ / 2⌋
mid' := mid - lo + 1
fork parallelMergesort
parallelMergesort
join
parallelMerge
In order to analyze a Recurrence relation for the worst case span, the recursive calls of parallelMergesort have to be incorporated only once due to their parallel execution, obtaining
For detailed information about the complexity of the parallel merge procedure, see Merge algorithm.
The solution of this recurrence is given by
This parallel merge algorithm reaches a parallelism of, which is much higher than the parallelism of the previous algorithm. Such a sort can perform well in practice when combined with a fast stable sequential sort, such as insertion sort, and a fast sequential merge as a base case for merging small arrays.

Parallel multiway merge sort

It seems arbitrary to restrict the merge sort algorithms to a binary merge method, since there are usually p > 2 processors available. A better approach may be to use a K-way merge method, a generalization of binary merge, in which sorted sequences are merged together. This merge variant is well suited to describe a sorting algorithm on a PRAM.

Basic Idea

Given an unsorted sequence of elements, the goal is to sort the sequence with available processors. These elements are distributed equally among all processors and sorted locally using a sequential Sorting algorithm. Hence, the sequence consists of sorted sequences of length. For simplification let be a multiple of, so that for.
These sequences will be used to perform a multisequence selection/splitter selection. For, the algorithm determines splitter elements with global rank. Then the corresponding positions of in each sequence are determined with binary search and thus the are further partitioned into subsequences with.
Furthermore, the elements of are assigned to processor, means all elements between rank and rank, which are distributed over all. Thus, each processor receives a sequence of sorted sequences. The fact that the rank of the splitter elements was chosen globally, provides two important properties: On the one hand, was chosen so that each processor can still operate on elements after assignment. The algorithm is perfectly load-balanced. On the other hand, all elements on processor are less than or equal to all elements on processor. Hence, each processor performs the p-way merge locally and thus obtains a sorted sequence from its sub-sequences. Because of the second property, no further p-way-merge has to be performed, the results only have to be put together in the order of the processor number.

Multisequence selection

In its simplest form, given sorted sequences distributed evenly on processors and a rank, the task is to find an element with a global rank in the union of the sequences. Hence, this can be used to divide each in two parts at a splitter index, where the lower part contains only elements which are smaller than, while the elements bigger than are located in the upper part.
The presented sequential algorithm returns the indices of the splits in each sequence, e.g. the indices in sequences such that has a global rank less than and.
algorithm msSelect is
for i = 1 to p do
=

while there exists i: l_i < r_i do
//pick Pivot Element in S_j,..,S_j, chose random j uniformly
v := pickPivot
for i = 1 to p do
m_i = binarySearch //sequentially
if m_1 +... + m_p >= k then //m_1+... + m_p is the global rank of v
r := m //vector assignment
else
l := m

return l
For the complexity analysis the PRAM model is chosen. If the data is evenly distributed over all, the p-fold execution of the binarySearch method has a running time of . The expected recursion depth is as in the ordinary Quickselect. Thus the overall expected running time is.
Applied on the parallel multiway merge sort, this algorithm has to be invoked in parallel such that all splitter elements of rank for are found simultaneously. These splitter elements can then be used to partition each sequence in parts, with the same total running time of.

Pseudocode

Below, the complete pseudocode of the parallel multiway merge sort algorithm is given. We assume that there is a barrier synchronization before and after the multisequence selection such that every processor can determine the splitting elements and the sequence partition properly.
/**
* d: Unsorted Array of Elements
* n: Number of Elements
* p: Number of Processors
* return Sorted Array
*/
algorithm parallelMultiwayMergesort is
o := new Array // the output array
for i = 1 to p do in parallel // each processor in parallel
S_i := d // Sequence of length n/p
sort // sort locally
synch
v_i := msSelect // element with global rank i * n/p
synch
:= sequence_partitioning // split s_i into subsequences

o := kWayMerge // merge and assign to output array

return o

Analysis

Firstly, each processor sorts the assigned elements locally using a sorting algorithm with complexity. After that, the splitter elements have to be calculated in time. Finally, each group of splits have to be merged in parallel by each processor with a running time of using a sequential p-way merge algorithm. Thus, the overall running time is given by

Practical adaption and application

The multiway merge sort algorithm is very scalable through its high parallelization capability, which allows the use of many processors. This makes the algorithm a viable candidate for sorting large amounts of data, such as those processed in computer clusters. Also, since in such systems memory is usually not a limiting resource, the disadvantage of space complexity of merge sort is negligible. However, other factors become important in such systems, which are not taken into account when modelling on a PRAM. Here, the following aspects need to be considered: Memory hierarchy, when the data does not fit into the processors cache, or the communication overhead of exchanging data between processors, which could become a bottleneck when the data can no longer be accessed via the shared memory.
Sanders et al. have presented in their paper a bulk synchronous parallel algorithm for multilevel multiway mergesort, which divides processors into groups of size. All processors sort locally first. Unlike single level multiway mergesort, these sequences are then partitioned into parts and assigned to the appropriate processor groups. These steps are repeated recursively in those groups. This reduces communication and especially avoids problems with many small messages. The hierarchial structure of the underlying real network can be used to define the processor groups.

Further Variants

Merge sort was one of the first sorting algorithms where optimal speed up was achieved, with Richard Cole using a clever subsampling algorithm to ensure O merge. Other sophisticated parallel sorting algorithms can achieve the same or better time bounds with a lower constant. For example, in 1991 David Powers described a parallelized quicksort that can operate in O time on a CRCW parallel random-access machine with n processors by performing partitioning implicitly. Powers further shows that a pipelined version of Batcher's Bitonic Mergesort at O time on a butterfly sorting network is in practice actually faster than his O sorts on a PRAM, and he provides detailed discussion of the hidden overheads in comparison, radix and parallel sorting.

Comparison with other sort algorithms

Although heapsort has the same time bounds as merge sort, it requires only Θ auxiliary space instead of merge sort's Θ. On typical modern architectures, efficient quicksort implementations generally outperform mergesort for sorting RAM-based arrays. On the other hand, merge sort is a stable sort and is more efficient at handling slow-to-access sequential media. Merge sort is often the best choice for sorting a linked list: in this situation it is relatively easy to implement a merge sort in such a way that it requires only Θ extra space, and the slow random-access performance of a linked list makes some other algorithms perform poorly, and others completely impossible.
As of Perl 5.8, merge sort is its default sorting algorithm. In Java, the methods use merge sort or a tuned quicksort depending on the datatypes and for implementation efficiency switch to insertion sort when fewer than seven array elements are being sorted. The Linux kernel uses merge sort for its linked lists. Python uses Timsort, another tuned hybrid of merge sort and insertion sort, that has become the standard sort algorithm in Java SE 7, on the Android platform, and in GNU Octave.