HOME

TheInfoList



OR:

In
computer science Computer science is the study of computation, automation, and information. Computer science spans theoretical disciplines (such as algorithms, theory of computation, information theory, and automation) to Applied science, practical discipli ...
, merge sort (also commonly spelled as mergesort) is an efficient, general-purpose, and comparison-based
sorting algorithm In computer science, a sorting algorithm is an algorithm that puts elements of a List (computing), list into an Total order, order. The most frequently used orders are numerical order and lexicographical order, and either ascending or descending. ...
. Most implementations produce a
stable sort In computer science, a sorting algorithm is an algorithm that puts elements of a list into an order. The most frequently used orders are numerical order and lexicographical order, and either ascending or descending. Efficient sorting is important ...
, which means that the order of equal elements is the same in the input and output. Merge sort is a
divide-and-conquer algorithm In computer science, divide and conquer is an algorithm design paradigm. A divide-and-conquer algorithm recursively breaks down a problem into two or more sub-problems of the same or related type, until these become simple enough to be solved dire ...
that was invented by
John von Neumann John von Neumann (; hu, Neumann János Lajos, ; December 28, 1903 – February 8, 1957) was a Hungarian-American mathematician, physicist, computer scientist, engineer and polymath. He was regarded as having perhaps the widest cove ...
in 1945. A detailed description and analysis of bottom-up merge sort appeared in a report by Goldstine and von Neumann as early as 1948.


Algorithm

Conceptually, a merge sort works as follows: #Divide the unsorted list into ''n'' sublists, each containing one element (a list of one element is considered sorted). #Repeatedly
merge Merge, merging, or merger may refer to: Concepts * Merge (traffic), the reduction of the number of lanes on a road * Merge (linguistics), a basic syntactic operation in generative syntax in the Minimalist Program * Merger (politics), the comb ...
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 (called ''runs'' in this example) 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 (except for an initial one-time copy, that can be avoided too). To help understand this, consider an array with two elements. The elements are copied to B[], then merged back to A[]. If there are four elements, when the bottom of the recursion level is reached, single element runs from A[] are merged to B[], and then at the next higher level of recursion, those two-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(A[], B[], n) // Split A[] into 2 runs, sort both runs into B[], merge both runs from B[] to A[] // iBegin is inclusive; iEnd is exclusive (A[iEnd] is not in the set). void TopDownSplitMerge(B[], iBegin, iEnd, A[]) // Left source half is A[ iBegin:iMiddle-1]. // Right source half is A Middle:iEnd-1 // Result is B iBegin:iEnd-1 void TopDownMerge(A[], iBegin, iMiddle, iEnd, B[]) void CopyArray(A[], iBegin, iEnd, B[]) 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 (called ''runs'' in this example) 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(A[], B[], n) // Left run is A[iLeft :iRight-1]. // Right run is A[iRight:iEnd-1 ]. void BottomUpMerge(A[], iLeft, iRight, iEnd, B[]) void CopyArray(B[], A[], n)


Top-down implementation using lists

Pseudocode In computer science, pseudocode is a plain language description of the steps in an algorithm or another system. Pseudocode often uses structural conventions of a normal programming language, but is intended for human reading rather than machine re ...
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(''list'' m) 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 < (length of m)/2 then add x to left else add x to right // ''Recursively sort both sublists.'' left := merge_sort(left) right := merge_sort(right) // Then merge the now-sorted sublists. return merge(left, right) In this example, the function merges the left and right sublists. function merge(left, right) is var result := empty list while left is not empty and right is not empty do if first(left) ≤ first(right) then append first(left) to result left := rest(left) else append first(right) to result right := rest(right) // ''Either left or right may have elements left; consume them.'' // ''(Only one of the following loops will actually be entered.)'' while left is not empty do append first(left) to result left := rest(left) while right is not empty do append first(right) to result right := rest(right) return result


Bottom-up implementation using lists

Pseudocode In computer science, pseudocode is a plain language description of the steps in an algorithm or another system. Pseudocode often uses structural conventions of a normal programming language, but is intended for human reading rather than machine re ...
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 2''i'' or ''
nil Nil may refer to: * nil (the number 0, zero) Acronyms * NIL (programming language), an implementation of the Lisp programming language * Student athlete compensation, Name, Image and Likeness, a set of rules in the American National Collegiate At ...
''. ''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(''node'' head) is // return if empty list if head = nil then return nil var ''node'' array 2 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 (i = 0; (i < 32) && (array ≠ nil); i += 1) do result := merge(array result) 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 (i = 0; i < 32; i += 1) do result := merge(array result) return result


Analysis

In sorting ''n'' objects, merge sort has an
average In ordinary language, an average is a single number taken as representative of a list of numbers, usually the sum of the numbers divided by how many numbers are in the list (the arithmetic mean). For example, the average of the numbers 2, 3, 4, 7, ...
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 relation In mathematics, a recurrence relation is an equation according to which the nth term of a sequence of numbers is equal to some combination of the previous terms. Often, only k previous terms of the sequence appear in the equation, for a parameter ...
''T''(''n'') = 2''T''(''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. The number of comparisons made by merge sort in the worst case is given by the
sorting number In mathematics and computer science, the sorting numbers are a sequence of numbers introduced in 1950 by Hugo Steinhaus for the analysis of comparison sort algorithms. These numbers give the worst-case number of comparisons used by both binary ins ...
s. These numbers are equal to or slightly smaller than (''n'' ⌈ lg ''n''⌉ − 2⌈lg ''n''⌉ + 1), which is between (''n'' lg ''n'' − ''n'' + 1) and (''n'' lg ''n'' + ''n'' + O(lg ''n'')). Merge sort's best case takes about half as many iterations as its worst case. 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_^\infty \frac1 \approx 0.2645. In the ''worst'' case, merge sort uses approximately 39% fewer comparisons than
quicksort Quicksort is an efficient, general-purpose sorting algorithm. Quicksort was developed by British computer scientist Tony Hoare in 1959 and published in 1961, it is still a commonly used algorithm for sorting. Overall, it is slightly faster than ...
does in its ''average'' case, and in terms of moves, merge sort's worst case complexity is O(''n'' log ''n'') - the same complexity as quicksort's best 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 A lisp is a speech impairment in which a person misarticulates sibilants (, , , , , , , ). These misarticulations often result in unclear speech. Types * A frontal lisp occurs when the tongue is placed anterior to the target. Interdental lisping ...
, 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 variations that need only ''n''/2 extra spaces).


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 Timsort is a hybrid, stable sorting algorithm, derived from merge sort and insertion sort, designed to perform well on many kinds of real-world data. It was implemented by Tim Peters in 2002 for use in the Python programming language. The algor ...
. 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) Formally, the natural merge sort is said to be Runs-optimal, where \mathtt(L) is the number of runs in L, minus one. Tournament replacement selection sorts are used to gather the initial runs for external sorting algorithms.


Ping-pong merge sort

Instead of merging two blocks at a time, a ping-pong merge merges four blocks at a time. The four sorted blocks are merged simultaneously to auxiliary space into two sorted blocks, then the two sorted blocks are merged back to main memory. Doing so omits the copy operation and reduces the total number of moves by half. An early public domain implementation of a four-at-once merge was by WikiSort in 2014, the method was later that year described as an optimization for
patience sorting In computer science, patience sorting is a sorting algorithm inspired by, and named after, the card game patience. A variant of the algorithm efficiently computes the length of a longest increasing subsequence in a given array. Overview The algor ...
and named a ping-pong merge. Quadsort implemented the method in 2020 and named it a quad merge.


In-place merge sort

One drawback of merge sort, when implemented on arrays, is its working memory requirement. Several methods to reduce memory or make merge sort fully
in-place In computer science, an in-place algorithm is an algorithm which transforms input using no auxiliary data structure. However, a small amount of extra storage space is allowed for auxiliary variables. The input is usually overwritten by the output ...
have been suggested: * suggested an alternative version of merge sort that uses constant additional space. * 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 pointers into the input array. They achieve an 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 time using a constant amount of scratch space, but their algorithm is complicated and has high constant factors: merging arrays of length and can take 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 time in total and is stable. Plugging such an algorithm into merge sort increases its complexity to the non-
linearithmic In computer science, the time complexity is the computational complexity that describes the amount of computer time it takes to run an algorithm. Time complexity is commonly estimated by counting the number of elementary operations performed by ...
, but still
quasilinear Quasilinear may refer to: * Quasilinear function, a function that is both quasiconvex and quasiconcave * Quasilinear utility, an economic utility function linear in one argument * In complexity theory and mathematics, O(''n'' log ''n'') or some ...
, . * Many applications of
external sorting External sorting is a class of sorting algorithms that can handle massive amounts of data. External sorting is required when the data being sorted do not fit into the main memory of a computing device (usually RAM) and instead they must reside in t ...
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 Page most commonly refers to: * Page (paper), one side of a leaf of paper, as in a book Page, PAGE, pages, or paging may also refer to: Roles * Page (assistance occupation), a professional occupation * Page (servant), traditionally a young mal ...
fit into main memory. * A modern stable linear and in-place merge variant is block merge sort which creates a section of unique values to use as swap space. * The space overhead can be reduced to sqrt(''n'') by using binary searches and rotations. This method is employed by the C++ STL library and quadsort. * 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. * A simple way to reduce 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.


Use with tape drives

An
external External may refer to: * External (mathematics), a concept in abstract algebra * Externality In economics, an externality or external cost is an indirect cost or benefit to an uninvolved third party that arises as an effect of another party' ...
merge sort is practical to run using
disk Disk or disc may refer to: * Disk (mathematics), a geometric shape * Disk storage Music * Disc (band), an American experimental music band * ''Disk'' (album), a 1995 EP by Moby Other uses * Disk (functional analysis), a subset of a vector sp ...
or tape drives when the data to be sorted is too large to fit into
memory Memory is the faculty of the mind by which data or information is encoded, stored, and retrieved when needed. It is the retention of information over time for the purpose of influencing future action. If past events could not be remembered, ...
.
External sorting External sorting is a class of sorting algorithms that can handle massive amounts of data. External sorting is required when the data being sorted do not fit into the main memory of a computing device (usually RAM) and instead they must reside in t ...
explains how merge sort is implemented with disk drives. 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 two record buffers, the algorithm is similar to the bottom-up implementation, using pairs of tape drives instead of arrays in memory. The basic algorithm can be described as follows: # Merge pairs of records from A; writing two-record sublists alternately to C and D. # Merge two-record sublists from C and D into four-record sublists; writing these alternately to A and B. # Merge four-record sublists from A and B into eight-record sublists; writing these alternately to C and D # Repeat until you have one list containing all the data, sorted—in log2(''n'') passes. Instead of starting with very short runs, usually a
hybrid algorithm {{Unreferenced, date=May 2014 A hybrid algorithm is an algorithm that combines two or more other algorithms that solve the same problem, and is mostly used in programming languages like C++, either choosing one (depending on the data), or switching ...
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. One of them, the Knuth's 'snowplow' (based on a binary min-heap), generates runs twice as long (on average) as a size of memory used. 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'' > two 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

On modern computers,
locality of reference In computer science, locality of reference, also known as the principle of locality, is the tendency of a processor to access the same set of memory locations repetitively over a short period of time. There are two basic types of reference localit ...
can be of paramount importance in
software optimization In computer science, program optimization, code optimization, or software optimization, is the process of modifying a software system to make some aspect of it work more efficiently or use fewer resources. In general, a computer program may be o ...
, because multilevel memory hierarchies are used.
Cache Cache, caching, or caché may refer to: Places United States * Cache, Idaho, an unincorporated community * Cache, Illinois, an unincorporated community * Cache, Oklahoma, a city in Comanche County * Cache, Utah, Cache County, Utah * Cache County ...
-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 Insertion sort is a simple sorting algorithm that builds the final sorted array (or list) one item at a time by comparisons. It is much less efficient on large lists than more advanced algorithms such as quicksort, heapsort, or merge sort. Ho ...
, 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.


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 Merge algorithms are a family of algorithms that take multiple sorted lists as input and produce a single list as output, containing all the elements of the inputs lists in sorted order. These algorithms are used as subroutines in various sorting ...
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 (containing one or no element). 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 (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 the trivial modification of the sequential version and does not parallelize well. Therefore, its speedup is not very impressive. It has a
span Span may refer to: Science, technology and engineering * Span (unit), the width of a human hand * Span (engineering), a section between two intermediate supports * Wingspan, the distance between the wingtips of a bird or aircraft * Sorbitan ester ...
of \Theta(n), which is only an improvement of \Theta(\log n) compared to the sequential version (see
Introduction to Algorithms ''Introduction to Algorithms'' is a book on computer programming by Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein. The book has been widely used as the textbook for algorithms courses at many universities and is co ...
). 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 Merge algorithms are a family of algorithms that take multiple sorted lists as input and produce a single list as output, containing all the elements of the inputs lists in sorted order. These algorithms are used as subroutines in various sorting ...
. Cormen et al. present a binary variant that merges two sorted sub-sequences into one sorted output sequence. In one of the sequences (the longer one if unequal length), 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 (adopted from Cormen et al.). /** * A: Input array * B: Output array * lo: lower bound * hi: upper bound * off: offset */ algorithm parallelMergesort(A, lo, hi, B, off) is len := hi - lo + 1 if len

1 then B ff:= A o/nowiki> else let T ..lenbe a new array mid := ⌊(lo + hi) / 2⌋ mid' := mid - lo + 1 fork parallelMergesort(A, lo, mid, T, 1) parallelMergesort(A, mid + 1, hi, T, mid' + 1) join parallelMerge(T, 1, mid', mid' + 1, len, B, off) In order to analyze a
recurrence relation In mathematics, a recurrence relation is an equation according to which the nth term of a sequence of numbers is equal to some combination of the previous terms. Often, only k previous terms of the sequence appear in the equation, for a parameter ...
for the worst case span, the recursive calls of parallelMergesort have to be incorporated only once due to their parallel execution, obtaining T_^(n) = T_^\left(\frac \right) + T_^(n) = T_^\left(\frac \right) + \Theta \left( \log(n)^2\right). For detailed information about the complexity of the parallel merge procedure, see
Merge algorithm Merge algorithms are a family of algorithms that take multiple sorted lists as input and produce a single list as output, containing all the elements of the inputs lists in sorted order. These algorithms are used as subroutines in various sorting ...
. The solution of this recurrence is given by T_^ = \Theta \left ( \log(n)^3 \right). This parallel merge algorithm reaches a parallelism of \Theta \left(\frac\right), 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 Insertion sort is a simple sorting algorithm that builds the final sorted array (or list) one item at a time by comparisons. It is much less efficient on large lists than more advanced algorithms such as quicksort, heapsort, or merge sort. Ho ...
, 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 Merge algorithms are a family of algorithms that take multiple sorted lists as input and produce a single list as output, containing all the elements of the inputs lists in sorted order. These algorithms are used as subroutines in various sorting ...
method, a generalization of binary merge, in which k sorted sequences are merged. This merge variant is well suited to describe a sorting algorithm on a PRAM.


Basic Idea

Given an unsorted sequence of n elements, the goal is to sort the sequence with p available
processors A central processing unit (CPU), also called a central processor, main processor or just processor, is the electronic circuitry that executes instructions comprising a computer program. The CPU performs basic arithmetic, logic, controlling, ...
. These elements are distributed equally among all processors and sorted locally using a sequential
Sorting algorithm In computer science, a sorting algorithm is an algorithm that puts elements of a List (computing), list into an Total order, order. The most frequently used orders are numerical order and lexicographical order, and either ascending or descending. ...
. Hence, the sequence consists of sorted sequences S_1, ..., S_p of length \lceil \frac \rceil. For simplification let n be a multiple of p, so that \left\vert S_i \right\vert = \frac for i = 1, ..., p. These sequences will be used to perform a multisequence selection/splitter selection. For j = 1,..., p, the algorithm determines splitter elements v_j with global rank k = j \frac. Then the corresponding positions of v_1, ..., v_p in each sequence S_i are determined with
binary search In computer science, binary search, also known as half-interval search, logarithmic search, or binary chop, is a search algorithm that finds the position of a target value within a sorted array. Binary search compares the target value to the m ...
and thus the S_i are further partitioned into p subsequences S_, ..., S_ with S_ := \. Furthermore, the elements of S_, ..., S_ are assigned to processor i, means all elements between rank (i-1) \frac and rank i \frac, which are distributed over all S_i. Thus, each processor receives a sequence of sorted sequences. The fact that the rank k of the splitter elements v_i was chosen globally, provides two important properties: On the one hand, k was chosen so that each processor can still operate on n/p elements after assignment. The algorithm is perfectly load-balanced. On the other hand, all elements on processor i are less than or equal to all elements on processor i+1. 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.


Multi-sequence selection

In its simplest form, given p sorted sequences S_1, ..., S_p distributed evenly on p processors and a rank k, the task is to find an element x with a global rank k in the union of the sequences. Hence, this can be used to divide each S_i in two parts at a splitter index l_i, where the lower part contains only elements which are smaller than x, while the elements bigger than x are located in the upper part. The presented sequential algorithm returns the indices of the splits in each sequence, e.g. the indices l_i in sequences S_i such that S_i _i/math> has a global rank less than k and \mathrm\left(S_i _i+1right) \ge k. algorithm msSelect(S : Array of sorted Sequences _1,..,S_p k : int) is for i = 1 to p do (l_i, r_i) = (0, , S_i, -1) while there exists i: l_i < r_i do // pick Pivot Element in S_j _j .., S_j _j chose random j uniformly v := pickPivot(S, l, r) for i = 1 to p do m_i = binarySearch(v, S_i _i, r_i // 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 p, the p-fold execution of the ''binarySearch'' method has a running time of \mathcal\left(p\log\left(n/p\right)\right). The expected recursion depth is \mathcal\left(\log\left( \textstyle \sum_i , S_i, \right)\right) = \mathcal(\log(n)) as in the ordinary
Quickselect In computer science, quickselect is a selection algorithm to find the ''k''th smallest element in an unordered list. It is also known as the kth order statistics . It is related to the quicksort sorting algorithm. Like quicksort, it was devel ...
. Thus the overall expected running time is \mathcal\left(p\log(n/p)\log(n)\right). Applied on the parallel multiway merge sort, this algorithm has to be invoked in parallel such that all splitter elements of rank i \frac n p for i = 1,.., p are found simultaneously. These splitter elements can then be used to partition each sequence in p parts, with the same total running time of \mathcal\left(p\, \log(n/p)\log(n)\right).


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(d : Array, n : int, p : int) is o := new Array , n // the output array for i = 1 to p do in parallel // each processor in parallel S_i := d i-1) * n/p, i * n/p // Sequence of length n/p sort(S_i) // sort locally synch v_i := msSelect( _1,...,S_p i * n/p) // element with global rank i * n/p synch (S_i,1, ..., S_i,p) := sequence_partitioning(si, v_1, ..., v_p) // split s_i into subsequences o i-1) * n/p, i * n/p:= kWayMerge(s_1,i, ..., s_p,i) // merge and assign to output array return o


Analysis

Firstly, each processor sorts the assigned n/p elements locally using a sorting algorithm with complexity \mathcal\left( n/p \; \log ( n/p) \right). After that, the splitter elements have to be calculated in time \mathcal\left(p \,\log(n/p) \log (n) \right). Finally, each group of p splits have to be merged in parallel by each processor with a running time of \mathcal(\log(p)\; n/p ) using a sequential p-way merge algorithm. Thus, the overall running time is given by \mathcal\left( \frac n p \log\left(\frac n p\right) + p \log \left( \frac n p\right) \log (n) + \frac n p \log (p) \right).


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 cluster A computer cluster is a set of computers that work together so that they can be viewed as a single system. Unlike grid computers, computer clusters have each node set to perform the same task, controlled and scheduled by software. The comp ...
s. 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 The bulk synchronous parallel (BSP) abstract computer is a bridging model for designing parallel algorithms. It is similar to the parallel random access machine (PRAM) model, but unlike PRAM, BSP does not take communication and synchronization fo ...
algorithm for multilevel multiway mergesort, which divides p processors into r groups of size p'. All processors sort locally first. Unlike single level multiway mergesort, these sequences are then partitioned into r 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 hierarchical structure of the underlying real network can be used to define the processor groups (e.g.
racks Rack or racks may refer to: Storage and installation * Amp rack, short for amplifier rack, a piece of furniture in which amplifiers are mounted * Bicycle rack, a frame for storing bicycles when not in use * Bustle rack, a type of storage bin m ...
, clusters,...).


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''(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 Quicksort is an efficient, general-purpose sorting algorithm. Quicksort was developed by British computer scientist Tony Hoare in 1959 and published in 1961, it is still a commonly used algorithm for sorting. Overall, it is slightly faster than ...
(and a related
radix sort In computer science, radix sort is a non-comparative sorting algorithm. It avoids comparison by creating and distributing elements into buckets according to their radix. For elements with more than one significant digit, this bucketing process i ...
) that can operate in ''O''(log ''n'') time on a CRCW
parallel random-access machine In computer science, a parallel random-access machine (parallel RAM or PRAM) is a shared-memory abstract machine. As its name indicates, the PRAM is intended as the parallel-computing analogy to the random-access machine (RAM) (not to be confused ...
(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 In computer science, comparator networks are abstract devices built up of a fixed number of "wires", carrying values, and comparator modules that connect pairs of wires, swapping the values on the wires if they are not in a desired order. Such net ...
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 In computer science, heapsort is a comparison-based sorting algorithm. Heapsort can be thought of as an improved selection sort: like selection sort, heapsort divides its input into a sorted and an unsorted region, and it iteratively shrinks the ...
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 Quicksort is an efficient, general-purpose sorting algorithm. Quicksort was developed by British computer scientist Tony Hoare in 1959 and published in 1961, it is still a commonly used algorithm for sorting. Overall, it is slightly faster than ...
implementations generally outperform merge sort 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 computer science, a linked list is a linear collection of data elements whose order is not given by their physical placement in memory. Instead, each element points to the next. It is a data structure consisting of a collection of nodes whic ...
: 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 Perl is a family of two high-level, general-purpose, interpreted, dynamic programming languages. "Perl" refers to Perl 5, but from 2000 to 2019 it also referred to its redesigned "sister language", Perl 6, before the latter's name was offici ...
5.8, merge sort is its default sorting algorithm (it was quicksort in previous versions of Perl). In
Java Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's List ...
, th
Arrays.sort()
methods use merge sort or a tuned quicksort depending on the datatypes and for implementation efficiency switch to
insertion sort Insertion sort is a simple sorting algorithm that builds the final sorted array (or list) one item at a time by comparisons. It is much less efficient on large lists than more advanced algorithms such as quicksort, heapsort, or merge sort. Ho ...
when fewer than seven array elements are being sorted. The
Linux Linux ( or ) is a family of open-source Unix-like operating systems based on the Linux kernel, an operating system kernel first released on September 17, 1991, by Linus Torvalds. Linux is typically packaged as a Linux distribution, which ...
kernel uses merge sort for its linked lists.
Python Python may refer to: Snakes * Pythonidae, a family of nonvenomous snakes found in Africa, Asia, and Australia ** ''Python'' (genus), a genus of Pythonidae found in Africa and Asia * Python (mythology), a mythical serpent Computing * Python (pro ...
uses
Timsort Timsort is a hybrid, stable sorting algorithm, derived from merge sort and insertion sort, designed to perform well on many kinds of real-world data. It was implemented by Tim Peters in 2002 for use in the Python programming language. The algor ...
, another tuned hybrid of merge sort and insertion sort, that has become the standard sort algorithm in
Java SE 7 The Java language has undergone several changes since JDK 1.0 as well as numerous additions of classes and packages to the standard library. Since J2SE 1.4, the evolution of the Java language has been governed by the Java Community P ...
(for arrays of non-primitive types), on the Android platform, and in
GNU Octave GNU Octave is a high-level programming language primarily intended for scientific computing and numerical computation. Octave helps in solving linear and nonlinear problems numerically, and for performing other numerical experiments using a langu ...
.


Notes


References

* *. Als
Practical In-Place Mergesort
Als

* * * * * *


External links

* – graphical demonstration
Open Data Structures - Section 11.1.1 - Merge Sort
Pat Morin Patrick Ryan Morin is a Canadian computer scientist specializing in computational geometry and data structures. He is a professor in the School of Computer Science at Carleton University. Education and career Morin was educated at Carleton Univers ...
{{DEFAULTSORT:Merge sort Sorting algorithms Comparison sorts Stable sorts Articles with example pseudocode Divide-and-conquer algorithms