Merge sort

From Wikipedia, the free encyclopedia
Jump to navigation Jump to search
Merge sort
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.
ClassSorting algorithm
Data structureArray
Worst-case performanceO(n log n)
Best-case performanceO(n log n) typical, O(n) natural variant
Average performanceO(n log n)
Worst-case space complexityО(n) total with O(n) auxiliary, O(1) auxiliary with linked lists[1]

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.[2] A detailed description and analysis of bottom-up mergesort appeared in a report by Goldstine and von Neumann as early as 1948.[3]


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.[4]

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

Top-down implementation[edit]

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)
	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);
		B[0] = 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);
		} else {
			nb = nb - 1;
			C[na + nb] = B[nb];
			if (nb == 0) {
				CopyArray(A, na, C);

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

Bottom-up implementation[edit]

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)

	// 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[0] = 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[0] = 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);
		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[edit]

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;
	// Additional fields as required

struct node *TopDownMergeSort(struct node *head, size_t n)
	struct node *sorted;
	if (n == 0)
		sorted = head;
		sorted = TopDownMergeSort2(&head, n);
	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
		*headp = first->next;
		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)
	struct node *head, **tailp = &head;

	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;
				return head;
		} else {
			*tailp = second;
			tailp = &second->next;
			second = second->next;
			if (second == NULL) {
				*tailp = first;
				return head;

Bottom-up implementation using lists[edit]

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 *TopDownMergeSort(struct node *head)
	struct node *array[ARRAY_SIZE] = { NULL };
	int i;

	while (head != NULL) {
		struct node *sorted = head;	// A sorted list of 1<<i elements

		head = head->next;
		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);
		array[i] = sorted;
	// Now merge all the partial lists
	for (i = 0; array[i] == NULL; i++)
		if (i == ARRAY_SIZE - 1)
			return NULL;
	head = array[i];
	for (; i < ARRAY_SIZE; i++)
		if (array[i] != NULL)
			head = MergeLists(array[i], head);
	return head;

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.[5]

Natural merge sort[edit]

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).[6] 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.


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)).[7]

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

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;[8] 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 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.[9]
  • 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.[10] This high constant factor and complicated in-place algorithm was made simpler and easier to understand. Bing-Chao Huang and Michael A. Langston[11] 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.[12] 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[edit]

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.[13]

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[edit]

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[edit]

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.[14] 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)
        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

time if enough processors are available.[14] 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.[15]

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.[16] 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.[17] Powers[18] 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[edit]

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.[19] The Linux kernel uses merge sort for its linked lists.[20] 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),[21] on the Android platform,[22] and in GNU Octave.[23]


  1. ^ Skiena (2008, p. 122)
  2. ^ Knuth (1998, p. 158)
  3. ^ Katajainen, Jyrki; Träff, Jesper Larsson (March 1997). "A meticulous analysis of mergesort programs" (PDF). Proceedings of the 3rd Italian Conference on Algorithms and Complexity. Italian Conference on Algorithms and Complexity. Rome. pp. 217–228. CiteSeerX doi:10.1007/3-540-62592-5_74.
  4. ^ Specifically it is External-Heapsort as described in Cantone, Domenico; Cincotti, Gianluca (August 2002). "QuickHeapsort, an efficient mix of classical sorting algorithms" (PDF). Theoretical Computer Science. 285 (1): 25–42. doi:10.1016/S0304-3975(01)00288-2.
  5. ^ "lib/list_sort.c". Linux kernel source code. 2019-06-20.
  6. ^ Powers, David M. W. and McMahon Graham B. (1983), "A compendium of interesting prolog programs", DCS Technical Report 8313, Department of Computer Science, University of New South Wales.
  7. ^ The worst case number given here does not agree with that given in Knuth's Art of Computer Programming, Vol 3. The discrepancy is due to Knuth analyzing a variant implementation of merge sort that is slightly sub-optimal
  8. ^ Cormen; Leiserson; Rivest; Stein. Introduction to Algorithms. p. 151. ISBN 978-0-262-03384-8.
  9. ^ Katajainen, Jyrki; Pasanen, Tomi; Teuhola, Jukka (1996). "Practical in-place mergesort". Nordic J. Computing. 3 (1): 27–40. CiteSeerX
  10. ^ Geffert, Viliam; Katajainen, Jyrki; Pasanen, Tomi (2000). "Asymptotically efficient in-place merging". Theoretical Computer Science. 237: 159–181. doi:10.1016/S0304-3975(98)00162-5.
  11. ^ Huang, Bing-Chao; Langston, Michael A. (March 1988). "Practical In-Place Merging". Communications of the ACM. 31 (3): 348–352. doi:10.1145/42392.42403.
  12. ^ Kim, Pok-Son; Kutzner, Arne (2004). Stable Minimum Storage Merging by Symmetric Comparisons. European Symp. Algorithms. Lecture Notes in Computer Science. 3221. pp. 714–723. CiteSeerX doi:10.1007/978-3-540-30140-0_63. ISBN 978-3-540-23025-0.
  13. ^ Selection sort. Knuth's snowplow. Natural merge.
  14. ^ a b Cormen et al. 2009, pp. 797–805
  15. ^ Victor J. Duvanenko "Parallel Merge Sort" Dr. Dobb's Journal & blog[1] and GitHub repo C++ implementation [2]
  16. ^ Cole, Richard (August 1988). "Parallel merge sort". SIAM J. Comput. 17 (4): 770–785. CiteSeerX doi:10.1137/0217049
  17. ^ Powers, David M. W. Parallelized Quicksort and Radixsort with Optimal Speedup, Proceedings of International Conference on Parallel Computing Technologies. Novosibirsk. 1991.
  18. ^ David M. W. Powers, Parallel Unification: Practical Complexity, Australasian Computer Architecture Workshop, Flinders University, January 1995
  19. ^ OpenJDK src/java.base/share/classes/java/util/ @ 53904:9c3fe09f69bc
  20. ^ linux kernel /lib/list_sort.c
  21. ^ jjb. "Commit 6804124: Replace "modified mergesort" in java.util.Arrays.sort with timsort". Java Development Kit 7 Hg repo. Archived from the original on 2018-01-26. Retrieved 24 Feb 2011.
  22. ^ "Class: java.util.TimSort<T>". Android JDK Documentation. Archived from the original on January 20, 2015. Retrieved 19 Jan 2015.
  23. ^ "liboctave/util/". Mercurial repository of Octave source code. Lines 23-25 of the initial comment block. Retrieved 18 Feb 2013. Code stolen in large part from Python's, listobject.c, which itself had no license header. However, thanks to Tim Peters for the parts of the code I ripped-off.


External links[edit]