Merge sort: Difference between revisions
Undid revision 476410105 by 123.237.16.124 (talk) incorrect |
Added a link to a book section |
||
Line 265: | Line 265: | ||
* [http://www.nist.gov/dads/HTML/mergesort.html Dictionary of Algorithms and Data Structures: Merge sort] |
* [http://www.nist.gov/dads/HTML/mergesort.html Dictionary of Algorithms and Data Structures: Merge sort] |
||
* [http://www.yorku.ca/sychen/research/sorting/index.html Mergesort applet] with "level-order" recursive calls to help improve algorithm analysis |
* [http://www.yorku.ca/sychen/research/sorting/index.html Mergesort applet] with "level-order" recursive calls to help improve algorithm analysis |
||
* [http://opendatastructures.org/versions/edition-0.1c/ods-java/node56.html#SECTION001411000000000000000 Open Data Structures - Section 11.1.1 - Merge Sort] |
|||
{{sorting}} |
{{sorting}} |
Revision as of 14:21, 2 March 2012
Class | Sorting algorithm |
---|---|
Data structure | Array |
Worst-case performance | O(n log n) |
Best-case performance | O(n log n) typical, O(n) natural variant |
Average performance | O(n log n) |
Worst-case space complexity | O(n) auxiliary |
Optimal | Yes |
Merge sort is an O(n log n) comparison-based sorting algorithm. Most implementations produce a stable sort, which means that the implementation preserves the input order of equal elements in the sorted output. Merge sort is a divide and conquer algorithm that was invented by John von Neumann in 1945.[1] A detailed description and analysis of bottom-up mergesort appeared in a report by Goldstine and Neumann as early as 1948.[2]
Algorithm
Conceptually, a merge sort works as follows
- Divide the unsorted list into n sublists, each containing 1 element (a list of 1 element is considered sorted).
- Repeatedly Merge sublists to produce new sublists until there is only 1 sublist remaining. (This will be the sorted list.)
Top-down implementation
Example pseudocode for top down merge sort algorithm which uses recursion to divide the list into sub-lists, then merges sublists during returns back up the call chain.
function merge_sort(list m) // if list size is 1, consider it sorted and return it if length(m) <= 1 return m // else list size is > 1, so split the list into two sublists var list left, right var integer middle = length(m) / 2 for each x in m up to middle add x to left for each x in m after or equal middle add x to right // recursively call merge_sort() to further split each sublist // until sublist size is 1 left = merge_sort(left) right = merge_sort(right) // merge the sublists returned from prior calls to merge_sort() // and return the resulting merged sublist return merge(left, right)
In this example, the merge
function merges the left and right sublists.
function merge(left, right) var list result while length(left) > 0 or length(right) > 0 if length(left) > 0 and length(right) > 0 if first(left) <= first(right) append first(left) to result left = rest(left) else append first(right) to result right = rest(right) else if length(left) > 0 append first(left) to result left = rest(left) else if length(right) > 0 append first(right) to result right = rest(right) end while return result
Bottom-up implementation
Example pseudocode 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 */
BottomUpSort(int n, array A[n], array B[n])
{
int width;
/* each 1-element run in A is already "sorted". */
/* Make successively longer sorted runs of length 2, 4, 8, 16... until whole array is sorted */
for (width = 1; width < n; width = 2 * width)
{
int i;
/* array A is full of runs of length width */
for (i = 0; i < n; i = i + 2 * width)
{
/* merge two runs: A[i:i+width-1] and A[i+width:i+2*width-1] to B[] */
/* or copy A[i:n-1] to B[] ( if(i+width >= n) ) */
BottomUpMerge(A, i, min(i+width, n), min(i+2*width, n), B);
}
/* now work array B is full of runs of length 2*width */
/* copy array B to array A for next iteration */
/* a more efficient implementation would swap the roles of A and B */
CopyArray(A, B, n);
/* now array A is full of runs of length 2*width */
}
}
BottomUpMerge(array A[], int iLeft, int iRight, int iEnd, array B[])
{
int i0 = iLeft;
int i1 = iRight;
int j;
/* while there are elements in the left or right lists */
for (j = iLeft; j < iEnd; j++)
{
/* if left list head exists and is <= existing right list head */
if (i0 < iRight && (i1 >= iEnd || A[i0] <= A[i1]))
{
B[j] = A[i0];
i0 = i0 + 1;
}
else
{
B[j] = A[i1];
i1 = i1 + 1;
}
}
}
Hybrid merge sort
A hybrid merge sort will use another sort algorithm to sort relatively small sub-lists:
- Divide the unsorted list into into some number of relatively small sublists and sort them using some sorting algorithm.
- Repeatedly Merge sublists to produce new sublists until there is only 1 sublist remaining. (This will be the sorted list.)
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. 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. For example, 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.
Analysis
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.
In the worst case, the number of comparisons merge sort makes is 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)).[3]
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; merge sort always makes fewer comparisons than quicksort, except in extremely rare cases, when they tie, where merge sort's worst case is found simultaneously with quicksort's best 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]
Recursive implementations of merge sort make 2n − 1 method calls in the worst case, compared to quicksort's n, thus merge sort has roughly twice as much recursive overhead as quicksort. However, iterative, non-recursive implementations of merge sort, avoiding method call overhead, are not difficult to code. 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).
Stable sorting in-place is possible but is more complicated, and usually a bit slower, even if the algorithm also runs in O(n log n) time (Katajainen, Pasanen & Teuhola 1996). One way to sort in-place is to merge the blocks recursively.[4] Like the standard merge sort, in-place merge sort is also a stable sort. Stable sorting of linked lists is simpler. In this case the algorithm does not use more space than that the already used by the list representation, but the O(log(k)) used for the recursion trace.
Merge sort is more efficient than quick sort 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 as long as the merge operation is implemented properly.
Merge sort also has some demerits. One is its use of 2n locations; the additional n locations are commonly used because merging two sorted sets in place is more complicated and would need more comparisons and move operations. But despite the use of this space the algorithm still does a lot of work: The contents of m are first copied into left and right and later into the list result on each invocation of merge_sort (variable names according to the pseudocode above). An alternative to this copying 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.
Another 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 in the previous paragraph is also mitigated, since the last pair of lines before the return result statement (function merge in the pseudo code above) become superfluous.
Merge sort can also be done with merging more than two sublists at a time, using the n-way merge algorithm. However, the number of operations is approximately the same. Consider merging k sublists at a time, where for simplicity k is a power of 2. The recurrence relation becomes T(n) = k T(n/k) + O(n log k). (The last part comes from the merge algorithm, which when implemented optimally using a heap or self-balancing binary search tree, takes O (log k) time per element.) If you take the recurrence relation for regular merge sort (T(n) = 2T(n/2) + O(n)) and expand it out log2k times, you get the same recurrence relation. This is true even if k is not a constant.
Use with tape drives
An external merge sort is practical to run using disk or tape drives when the data to be sorted is too large to fit into memory. External sorting explains how merge sort is implemented with disk drives. A typical tape drive sort uses four tape drives. All I/O is sequential (except for rewinds at the end of each pass). A minimal implementation can get by with just 2 record buffers and a few program variables.
Naming the four tape drives as A, B, C, D, with the original data on A, and using only 2 record buffers, the algorithm is similar to #Bottom-up_implementation, using pairs of tape drives instead of arrays in memory. The basic algorithm can be described as follows:
- 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, 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 9 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.[5]
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 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, 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. (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 processing
Merge sort parallelizes well due to use of divide-and-conquer method. A parallel implementation is shown in pseudo-code in the third edition of Cormen, Leiserson, and Stein's Introduction to Algorithms.[6] This algorithm uses parallel merge algorithm to not only parallelize the recursive division of the array, but also the merge operation. It performs 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.[7] 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.[8] 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 PRAM with n processors by performing partitioning implicitly.[9]
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), and is often faster in practical implementations. On typical modern architectures, efficient quicksort implementations generally outperform mergesort for sorting RAM-based arrays. On the other hand, merge sort is a stable sort, parallelizes better, 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.[10] Python uses timsort, another tuned hybrid of merge sort and insertion sort, which will also become the standard sort algorithm for Java SE 7.[11]
Utility in online sorting
Merge sort's merge operation is useful in online sorting, where the list to be sorted is received a piece at a time, instead of all at the beginning. In this application, we sort each new piece that is received using any sorting algorithm, and then merge it into our sorted list so far using the merge operation. However, this approach can be expensive in time and space if the received pieces are small compared to the sorted list — a better approach in this case is to insert elements into a binary search tree as they are received.
Notes
- ^ Knuth (1998, p. 158)
- ^ Jyrki Katajainen and Jesper Larsson Träff (1997). "A meticulous analysis of mergesort programs".
{{cite journal}}
: Cite journal requires|journal=
(help); Invalid|ref=harv
(help) - ^ 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
- ^ A Java implementation of in-place stable merge sort
- ^ Selection sort. Knuth's snowplow. Natural merge.
- ^ Cormen et al. 2009, p. 803
- ^ V. J. Duvanenko, "Parallel Merge Sort", Dr. Dobb's Journal, March 2011
- ^ Cole, Richard (1988). "Parallel merge sort". SIAM J. Comput. 17 (4): 770–785. doi:10.1137/0217049Template:Inconsistent citations
{{cite journal}}
: Invalid|ref=harv
(help); Unknown parameter|month=
ignored (help)CS1 maint: postscript (link) - ^ Powers, David M. W. Parallelized Quicksort and Radixsort with Optimal Speedup, Proceedings of International Conference on Parallel Computing Technologies. Novosibirsk. 1991.
- ^ OpenJDK Subversion
- ^ http://hg.openjdk.java.net/jdk7/tl/jdk/rev/bfd7abda8f79
References
- Cormen, Thomas H.; Leiserson, Charles E.; Rivest, Ronald L.; Stein, Clifford (2009) [1990]. Introduction to Algorithms (3rd ed.). MIT Press and McGraw-Hill. ISBN 0-262-03384-4.
- Katajainen, Jyrki; Pasanen, Tomi; Teuhola, Jukka (1996). "Practical in-place mergesort". Nordic Journal of Computing. Vol. 3. pp. 27–40. ISSN 1236-6064. Retrieved 2009-04-04.
{{cite news}}
: Invalid|ref=harv
(help). Also Practical In-Place Mergesort. Also [1] - Knuth, Donald (1998). "Section 5.2.4: Sorting by Merging". Sorting and Searching. The Art of Computer Programming. Vol. 3 (2nd ed.). Addison-Wesley. pp. 158–168. ISBN 0-201-89685-0.
{{cite book}}
: Invalid|ref=harv
(help) - Kronrod, M. A. (1969). "Optimal ordering algorithm without operational field". Soviet Mathematics - Doklady. Vol. 10. p. 744.
{{cite news}}
: Invalid|ref=harv
(help) - LaMarca, A.; Ladner, R. E. (1997). "The influence of caches on the performance of sorting". Proc. 8th Ann. ACM-SIAM Symp. on Discrete Algorithms (SODA97): 370–379.
{{cite journal}}
: Invalid|ref=harv
(help) - Sun Microsystems, Inc. "Arrays API". Retrieved 2007-11-19.
- Sun Microsystems, Inc. "java.util.Arrays.java". Retrieved 2007-11-19.
External links
- Animated Sorting Algorithms: Merge Sort – graphical demonstration and discussion of array-based merge sort
- Dictionary of Algorithms and Data Structures: Merge sort
- Mergesort applet with "level-order" recursive calls to help improve algorithm analysis
- Open Data Structures - Section 11.1.1 - Merge Sort