# Merge sort

Class An example of merge sort. First divide the list into the smallest unit (1 element), then compare each element with the adjacent list to sort and merge the two adjacent lists. Finally all the elements are sorted and merged. Sorting algorithm Array O(n log n) O(n log n) typical, O(n) natural variant O(n log n) О(n) total with O(n) auxiliary, O(1) auxiliary with linked lists

In computer science, merge sort (also commonly spelled mergesort) 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. A list of one element is inherently sorted.
2. Repeatedly merge sorted sublists (called "runs") to produce longer runs until there is only one run remaining. This is the sorted list.

The pattern of merges forms a tree structure; in the common case that binary (two-way) merges are used, it forms a binary tree. The merges must be performed according to a post-order traversal, but that still leaves considerable flexibility.

The most common choices are depth-first or breadth-first order. Mergesort is often explained using breadth-first order (do all 1+1-to-2 merges, then all 2+2-to-4, etc.), but practical implementations tend to use depth-first order (do the first 2+2-to-4 merge as soon as the first two 1+1-to-2 merges are complete, etc.), as that gives better locality of reference.

It is also possible to interleave the merges, generating the output of a smaller merge as needed by a larger merge. Limited to a finite number of levels, this is an efficient way to implement a 4- or 8-way merge and can further improve locality of reference. Taken to the extreme, the result resembles heapsort.

The examples which follow use binary, depth-first merging.

### 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. Careful ordering of the merging operations avoids excessive copying while keeping the size of the required work array to half the size of the input.

#include <stddef.h>	// For size_t
#include <assert.h>

// Array A[] has the items to sort; array B[] is a work array half the size of A[].
void TopDownMergeSort(int A[], size_t n, int B[])
{
if (n < 2)
return;
TopDownMergeSort2(A, n, B, A);
}

// Array A[] has the items to sort, of length n (which must be >= 2)
// B[] is a temporary array at least half the size of A
// C[] (which may be the same as A[] or B[]) is where the sorted result should go
void TopDownMergeSort2(int A[], size_t n, int B[], int C[])
{
size_t mid = (n + 1) / 2;	// Midpoint, rounding up

// Sort the first half in-place
if (mid > 1)
TopDownMergeSort2(A, mid, B, A);
// Sort the second half into B
if (n - mid > 1)
TopDownMergeSort2(A + mid, n - mid, B, B);
else
B = A[mid];
// Merge the two into C
MergeArray(A, mid, B, n - mid, C);
}

// Merge sorted lists A[] and B[] into C[].
// The merge is done from the end, working back to the beginning,
// so C[] may be the same array as A[] or B[].
void MergeArray(int A[], size_t na, int B[], size_t nb, int C[])
{
assert(na > 0);
assert(nb > 0);

for (;;) {
// If entries are equal, put the value from B[] last,
// so the sort remains stable.
if (A[na-1] < B[nb-1]) {
na = na - 1;
C[na + nb] = A[na];
if (na == 0) {
CopyArray(B, nb, C);
return;
}
} else {
nb = nb - 1;
C[na + nb] = B[nb];
if (nb == 0) {
CopyArray(A, na, C);
return;
}
}
}
}

void CopyArray(int A[], size_t n, int B[])
{
for (size_t i = 0; i < n; i++)
B[i] = A[i];
}


### Bottom-up implementation

Example C-like code using indices for bottom-up merge sort algorithm. This is implemented non-recursively.

The array A[] contains number of sorted lists, of total size na, followed by an unsorted suffix. The sorted lists are each a power of two size, corresponding to the 1 bits in the binary representation of na. The array B[] contains a single sorted list, of size nb.

This uses the MergeArray() function from the top-down implementation above. The lsbit() function is implemented using a well-known but non-obvious bit manipulation trick.

// array A[] has the items to sort; array B[] is a work array half the size of A.
void BottomUpMergeSort(int A[], size_t n, int B[])
{
size_t na, nb;

if (n < 2)
return;

// Only odd elements trigger merges, with the preceding even
// element.  Even elements are simply appended to A as a sorted
// list of length 1, so this loop skips them completely,
for (na = 1; na < n - 1; na = na + 2) {
B = A[na];
// Repeatedly merge B[] with the sorted list of length nb
// at the end of A[], as long as such a list exists.
// Do intermediate merges into B
for (nb = 1; (na & 2*nb) != 0; nb = 2*nb)
MergeArray(A + na + 1 - 2*nb, nb, B, nb, B);
// And the final merge into A
MergeArray(A + na + 1 - 2*nb, nb, B, nb, A + na + 1 - 2*nb);
}

// The final merge series is similar, but we merge all the
// sorted lists in A[] rather limiting nb to powers of two.
na = n - 1;
B = A[na];
nb = 1;

while (true) { // Infinite loop
// The size of the last sorted list in A[]
size_t t = lsbit(na);

na = na - t;
if (na == 0) {
MergeArray(A, t, B, nb, A);
return;
}
MergeArray(A + na, t, B, nb, B);
nb = nb + t;
}
}

// Return the least significant bit set in n, equal to
// the greatest power of 2 which divides n, i.e.
// Return 1 if n is odd
// Return 2 if n is even but not divisible by 4
// Return 4 if n is divisible by 4 but not 8
// etc.
size_t lsbit(size_t n)
{
return n & -n;
}


### Top-down implementation using lists

Example C-like code for top-down merge sort of a single-linked list. This 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.

The length of the list must be known before the subdivision can be started.

#include <stddef.h>

struct node {
struct node *next;
int key;
};

struct node *TopDownMergeSort(struct node *head, size_t n)
{
struct node *sorted;
if (n == 0)
else
assert(head == NULL);	// The list should be the length we were told
return sorted;
}

// Sort the first n > 0 elements of the given list.
// A sorted list of n is returned; the head is modified to point to the n+1st element.
struct node *TopDownMergeSort2(struct node **headp, size_t n)
{
struct node *first = *headp, second;

assert(n >= 1);
assert(first != NULL);
if (n == 1) {
// Detach and return the first entry as a sorted run
first->next = NULL;
return first;
}
// Recursively sort two sublists
first  = TopDownMergeSort2(headp, (n + 1) / 2);
second = TopDownMergeSort2(headp, n / 2);
// Merge the two together into one sorted list
return MergeLists(first, second);
}

// Merge the two lists.  Both must be non-NULL.
struct node *MergeLists(struct node *first, struct node *second)
{

assert(first  != NULL);
assert(second != NULL);

for (;;) {
if (first->key <= second->key) {
*tailp = first;
tailp = &first->next;
first = first->next;
if (first == NULL) {
*tailp = second;
}
} else {
*tailp = second;
tailp = &second->next;
second = second->next;
if (second == NULL) {
*tailp = first;
}
}
}
}


### Bottom-up implementation using lists

A bottom-up merge sort does not need to know the length of the list in advance. Instead of recursing, it keeps a small array of sorted sublists, where array[i] may be NULL or a pointer to a list of size 2i.

This uses the MergeLists function from the previous implementation.

#define ARRAY_SIZE 32

{
struct node *array[ARRAY_SIZE] = { NULL };
int i;

struct node *sorted = head;	// A sorted list of 1<<i elements

sorted->next = NULL;

for (i = 0; array[i] != NULL; i++) {
sorted = MergeLists(array[i], sorted);
array[i] = NULL;
// Gracefully (if inefficiently) handle inputs longer than 1 << ARRAY_SIZE
if (i == ARRAY_SIZE - 1);
break;
}
array[i] = sorted;
}
// Now merge all the partial lists
for (i = 0; array[i] == NULL; i++)
if (i == ARRAY_SIZE - 1)
return NULL;
for (; i < ARRAY_SIZE; i++)
if (array[i] != NULL)
}


Bottom-up implementations like this which merge as soon as 2i elements are available have the problem that the final (largest) merges can be very unbalanced, which is inefficient. (For example, sorting 513 items will have a final merge of one item with a list of 29 = 512.) Less eager algorithms which avoid this problem exist.

## Natural merge sort

A natural merge sort is similar to a bottom-up merge sort except that any naturally occurring runs (sorted sequences) in the input are exploited. Both monotonic and bitonic (alternating up/down) runs may be exploited, with lists (or equivalently tapes or files) being convenient data structures (used as FIFO queues or LIFO stacks). 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 (i.e., is one run), 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 : (3  4)(2)(1  7)(5  8  9)(0  6)
Merge       : (2  3  4)(1  5  7  8  9)(0  6)
Merge       : (1  2  3  4  5  7  8  9)(0  6)
Merge       : (0  1  2  3  4  5  6  7  8  9)


Tournament replacement selection sorts are used to gather the initial runs for external sorting algorithms.

## Analysis A recursive merge sort algorithm used to sort an array of 7 integer values. These are the steps a human would take to emulate merge sort (top-down).

In sorting n objects, merge sort has an average and worst-case performance of O(n log n). If the running time of merge sort for a list of length n is T(n), then the recurrence T(n) = 2T(n/2) + n follows from the definition of the algorithm (apply the algorithm to two lists of half the size of the original list, and add the n steps taken to merge the resulting two lists). 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 (n ⌈lg n⌉ − 2⌈lg n + 1), which is between (n lg nn + 1) and (n lg n + n + O(lg n)).

For large n and a randomly ordered input list, merge sort's expected (average) number of comparisons approaches α·n fewer than the worst case where $\alpha =-1+\sum _{k=0}^{\infty }{\frac {1}{2^{k}+1}}\approx 0.2645.$ 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(n log n)—the same complexity as quicksort's best case, and merge sort's best case takes about half as many iterations as the worst case.[citation needed]

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 (efficient) 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 (see below for versions that need only n/2 extra spaces).

## 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 (function merge in the pseudo code above) become superfluous.

One drawback of merge sort, when implemented on arrays, is its O(n) working memory requirement. Several in-place variants have been suggested:

• Katajainen et al. present an algorithm that requires a constant amount of working memory: enough storage space to hold one element of the input array, and additional space to hold O(1) pointers into the input array. They achieve an O(n log n) time bound with small constants, but their algorithm is not stable.
• Several attempts have been made at producing an in-place merge algorithm that can be combined with a standard (top-down or bottom-up) merge sort to produce an in-place merge sort. In this case, the notion of "in-place" can be relaxed to mean "taking logarithmic stack space", because standard merge sort requires that amount of space for its own stack usage. It was shown by Geffert et al. that in-place, stable merging is possible in O(n log n) time using a constant amount of scratch space, but their algorithm is complicated and has high constant factors: merging arrays of length n and m can take 5n + 12m + o(m) moves. This high constant factor and complicated in-place algorithm was made simpler and easier to understand. Bing-Chao Huang and Michael A. Langston presented a straightforward linear time algorithm practical in-place merge to merge a sorted list using fixed amount of additional space. They both have used the work of Kronrod and others. It merges in linear time and constant extra space. The algorithm takes little more average time than standard merge sort algorithms, free to exploit O(n) temporary extra memory cells, by less than a factor of two. Though the algorithm is much faster in a practical way but it is unstable also for some lists. But using similar concepts, they have been able to solve this problem. Other in-place algorithms include SymMerge, which takes O((n + m) log (n + m)) time in total and is stable. Plugging such an algorithm into merge sort increases its complexity to the non-linearithmic, but still quasilinear, O(n (log n)2).
• A modern stable linear and in-place merging is block merge sort.

An alternative to reduce the copying into multiple lists is to associate a new field of information with each key (the elements in m are called keys). This field will be used to link the keys and any associated information together in a sorted list (a key and its related information is called a record). 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 Merge sort type algorithms allowed large data sets to be sorted on early computers that had small random access memories by modern standards. Records were stored on magnetic tape and processed on banks of magnetic tape drives, such as these IBM 729s.

An external merge sort is practical to run using disk or tapes when the data to be sorted is too large to fit into memory. The implementation with disk drives is explained in external sorting A typical tape drive sort uses four tape drives. All I/O is sequential (except for rewinds at the end of each pass). 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 a breadth-first 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 runs alternately to C and D.
2. Merge two-record runs from C and D into four-record runs, writing these alternately to A and B.
3. Merge four-record runs from A and B into eight-record runs, writing these alternately to C and D
4. Repeat until you have one run containing all the data, sorted in log2(n) passes.

Instead of starting with single-record 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 tapes. The internal sort is made as large as possible because it avoids many early passes. For example, an internal sort of 1024 records will save nine passes. 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(n log n) running time can also be achieved using two queues, or a stack and a queue, or three stacks. In the other direction, using k > 4 tapes (and O(k) items in memory), we can reduce the number of tape operations in O(log k) times by using a k/2-way merge.

A more sophisticated merge sort that optimizes tape (and disk) drive usage is the polyphase merge sort.

## Optimizing merge sort Tiled merge sort applied to an array of random integers. The horizontal axis is the array index and the vertical axis is the integer.

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 tiled merge sort 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[example needed] on machines that benefit from cache optimization. (LaMarca & Ladner 1997)

Kronrod (1969) suggested an alternative version of merge sort that uses constant additional space. This algorithm was later refined. (Katajainen, Pasanen & Teuhola 1996)

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 use of the divide-and-conquer method. Several parallel variants are discussed in the third edition of Cormen, Leiserson, Rivest, and Stein's Introduction to Algorithms. The first of these can be very easily expressed in a pseudocode with fork and join keywords:

// Sort elements lo through hi (exclusive) of array A.
algorithm mergesort(A, lo, hi) is
if lo+1 < hi then  // Two or more elements.
mid := ⌊(lo + hi) / 2⌋
fork mergesort(A, lo, mid)
mergesort(A, mid, hi)
join
merge(A, lo, mid, hi)


This algorithm is a trivial modification from the serial version, and its speedup is not impressive: when executed on an infinite number of processors, it runs in Θ(n) time, which is only a Θ(log n) improvement on the serial version. A better result can be obtained by using a parallelized merge algorithm, which gives parallelism Θ(n / (log n)2), meaning that this type of parallel merge sort runs in

$\Theta \left((n\log n)\cdot {\frac {(\log n)^{2}}{n}}\right)=\Theta ((\log n)^{3})$ time if enough processors are available. 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.

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(1) 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 (and a related radix sort) that can operate in O(log n) time on a CRCW parallel random-access machine (PRAM) with n processors by performing partitioning implicitly. Powers further shows that a pipelined version of Batcher's Bitonic Mergesort at O((log n)2) time on a butterfly sorting network is in practice actually faster than his O(log n) 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 Θ(1) auxiliary space instead of merge sort's Θ(n). On typical modern architectures, efficient quicksort implementations generally outperform mergesort for sorting RAM-based arrays.[citation needed] 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 Θ(1) extra space, and the slow random-access performance of a linked list makes some other algorithms (such as quicksort) perform poorly, and others (such as heapsort) completely impossible.

As of Perl 5.8, merge sort is its default sorting algorithm (it was quicksort in previous versions of Perl). In Java, the Arrays.sort() 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 (for arrays of non-primitive types), on the Android platform, and in GNU Octave.