All Topics  
Merge sort

 
Merge Sort

   Email Print
   Bookmark   Link






 

Merge sort



 
 
Merge sort or merge_sort is an O
Big O notation

In mathematics, big O notation describes the asymptotic analysis of a function when the argument tends towards a particular value or infinity, usually in terms of simpler functions....
(n log n) comparison-based
Comparison sort

A comparison sort is a type of sorting algorithm that only reads the list elements through a single abstract comparison operation that determines which of two elements should occur first in the final sorted list....
 sorting algorithm
Sorting algorithm

In computer science and mathematics, a sorting algorithm is an algorithm that puts elements of a List in a certain Total order. The most-used orders are numerical order and lexicographical order....
. In most implementations it is stable
Sorting algorithm

In computer science and mathematics, a sorting algorithm is an algorithm that puts elements of a List in a certain Total order. The most-used orders are numerical order and lexicographical order....
, meaning that it preserves the input order of equal elements in the sorted output. It is an example of the divide and conquer
Divide and conquer algorithm

In computer science, divide and conquer is an important algorithm design paradigm based on multi-branched recursion. A divide and conquer algorithm works by recursively breaking down a problem into two or more sub-problems of the same type, until these become simple enough to be solved directly....
 algorithmic paradigm. It was invented by John von Neumann
John von Neumann

John von Neumann was a Hungarian American mathematician who made major contributions to a vast range of fields, including set theory, functional analysis, quantum mechanics, ergodic theory, continuous geometry, economics and game theory, computer science, numerical analysis, hydrodynamics , and statistics, as well as many other mathematical...
 in 1945.

eptually, a merge sort works as follows:
  1. If the list is of length 0 or 1, then it is already sorted.






    Discussion
    Ask a question about 'Merge sort'
    Start a new discussion about 'Merge sort'
    Answer questions from other users
    Full Discussion Forum



    Encyclopedia


    Merge sort or merge_sort is an O
    Big O notation

    In mathematics, big O notation describes the asymptotic analysis of a function when the argument tends towards a particular value or infinity, usually in terms of simpler functions....
    (n log n) comparison-based
    Comparison sort

    A comparison sort is a type of sorting algorithm that only reads the list elements through a single abstract comparison operation that determines which of two elements should occur first in the final sorted list....
     sorting algorithm
    Sorting algorithm

    In computer science and mathematics, a sorting algorithm is an algorithm that puts elements of a List in a certain Total order. The most-used orders are numerical order and lexicographical order....
    . In most implementations it is stable
    Sorting algorithm

    In computer science and mathematics, a sorting algorithm is an algorithm that puts elements of a List in a certain Total order. The most-used orders are numerical order and lexicographical order....
    , meaning that it preserves the input order of equal elements in the sorted output. It is an example of the divide and conquer
    Divide and conquer algorithm

    In computer science, divide and conquer is an important algorithm design paradigm based on multi-branched recursion. A divide and conquer algorithm works by recursively breaking down a problem into two or more sub-problems of the same type, until these become simple enough to be solved directly....
     algorithmic paradigm. It was invented by John von Neumann
    John von Neumann

    John von Neumann was a Hungarian American mathematician who made major contributions to a vast range of fields, including set theory, functional analysis, quantum mechanics, ergodic theory, continuous geometry, economics and game theory, computer science, numerical analysis, hydrodynamics , and statistics, as well as many other mathematical...
     in 1945.

    Algorithm

    Conceptually, a merge sort works as follows:
    1. If the list is of length 0 or 1, then it is already sorted. Otherwise:
    2. Divide the unsorted list into two sublists of about half the size.
    3. Sort each sublist recursively
      Recursion

      Recursion, in mathematics and computer science, is a method of defining Function in which the function being defined is applied within its own definition....
       by re-applying merge sort.
    4. Merge
      Merge algorithm

      Merge algorithms are a family of algorithms that run sequentially over multiple sorting algorithm lists, typically producing more sorted lists as output....
       the two sublists back into one sorted list.


    Merge sort incorporates two main ideas to improve its runtime:
    1. A small list will take fewer steps to sort than a large list.
    2. Fewer steps are required to construct a sorted list from two sorted lists than two unsorted lists. For example, you only have to traverse each list once if they're already sorted (see the merge
      Merge algorithm

      Merge algorithms are a family of algorithms that run sequentially over multiple sorting algorithm lists, typically producing more sorted lists as output....
       function below for an example implementation).


    Example: Using merge sort to sort a list of integers contained in an array
    Array

    In computer science, an array is a data structure consisting of a group of element s that are accessed by index . In most programming languages each element has the same data type and the array occupies a contiguous area of computer memory....
    :

    Suppose we have an array A with n indices ranging from to . We apply merge sort to and where c is the integer part of . When the two halves are returned they will have been sorted. They can now be merged together to form a sorted array.

    In a simple pseudocode
    Pseudocode

    Pseudocode is a compact and informal high-level description of a computer programming algorithm that uses the structural conventions of some programming language, but is intended for human reading rather than machine reading....
     form, the algorithm could look something like this:

    There are several variants for the merge function, the simplest variant could look like this:

    Analysis


    In sorting n items, merge sort has an average and worst-case performance of O
    Big O notation

    In mathematics, big O notation describes the asymptotic analysis of a function when the argument tends towards a particular value or infinity, usually in terms of simpler functions....
    (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
    Master theorem

    In the analysis of algorithms, the master theorem, which is a specific case of the Akra-Bazzi method, provides a cookbook solution in asymptotic terms for recurrence relations of types that occur in practice....
    .

    In the worst case, merge sort does approximately (n ?lg
    Binary logarithm

    In mathematics, the binary logarithm is the logarithm for base 2. It is the inverse function of ....
     n? - 2?lg n? + 1) comparisons, which is between (n lg n - n + 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 a·n fewer than the worst case where

    In the worst case, merge sort does about 39% fewer comparisons than quicksort
    Quicksort

    Quicksort is a well-known sorting algorithm developed by C. A. R. Hoare that, average performance, makes comparisons to sort n items. However, in the Best, worst and average case, it makes comparisons....
     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
    Big O notation

    In mathematics, big O notation describes the asymptotic analysis of a function when the argument tends towards a particular value or infinity, usually in terms of simpler functions....
    (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.

    Recursive implementations of merge sort make 2n - 1 method calls in the worst case, compared to quicksort's n, thus 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.

    Sorting in-place is possible but is very complicated, and will offer little performance gains in practice, even if the algorithm runs in O(n log n) time. In these cases, algorithms like heapsort
    Heapsort

    Heapsort is a comparison sort sorting algorithm, and is part of the selection sort family. Although somewhat slower in practice on most machines than a good implementation of quicksort, it has the advantage of a worst-case big O notation runtime....
     usually offer comparable speed, and are far less complex. Additionally, unlike the standard merge sort, in-place merge sort is not a stable sort.

    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
    Lisp programming language

    Lisp is a family of computer programming languages with a long history and a distinctive, fully parenthesized syntax. Originally specified in 1958, Lisp is the second-oldest high-level programming language in widespread use today; only Fortran is older....
    , 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.

    As can be seen from the procedure merge sort, there are some complaints. One complaint we might raise is its use of 2n locations; the additional n locations were needed because one couldn't reasonably merge two sorted sets in place. But despite the use of this space the algorithm must still work hard, copying the result placed into Result list back into m list on each call of merge . 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.

    Merge sorting tape drives

    Merge sort is so inherently sequential that it's practical to run it using slow tape drives as input and output devices. It requires very little memory, and the memory required does not change with the number of data elements.

    For the same reason it is also useful for sorting data on disk
    Disk storage

    Disk storage is a general category of a computer storage mechanisms, in which data is recorded on planar, round and rotating surfaces . A disk drive is a peripheral device used to record and retrieve information....
     that is too large to fit entirely into primary memory. On tape drives that can run both backwards and forwards, merge passes can be run in both directions, avoiding rewind time.

    If you have four tape drives, it works as follows:

    1. Divide the data to be sorted in half and put half on each of two tapes
    2. Merge individual pairs of records from the two tapes; write two-record chunks alternately to each of the two output tapes
    3. Merge the two-record chunks from the two output tapes into four-record chunks; write these alternately to the original two input tapes
    4. Merge the four-record chunks into eight-record chunks; write these alternately to the original two output tapes
    5. Repeat until you have one chunk containing all the data, sorted --- that is, for log n passes, where n is the number of records.


    For almost-sorted data on tape, a bottom-up "natural merge sort" variant of this algorithm is popular.

    The bottom-up "natural merge sort" merges whatever "chunks" of in-order records are already in the data. In the worst case (reversed data), "natural merge sort" performs the same as the above -- it merges individual records into 2-record chunks, then 2-record chunks into 4-record chunks, etc. In the best case (already mostly-sorted data), "natural merge sort" merges large already-sorted chunks into even larger chunks, hopefully finishing in fewer than log n passes.

    In a simple pseudocode
    Pseudocode

    Pseudocode is a compact and informal high-level description of a computer programming algorithm that uses the structural conventions of some programming language, but is intended for human reading rather than machine reading....
     form, the "natural merge sort" algorithm could look something like this:

    # Original data is on the input tape; the other tapes are blank function merge_sort(input_tape, output_tape, scratch_tape_C, scratch_tape_D) while any records remain on the input_tape while any records remain on the input_tape merge( input_tape, output_tape, scratch_tape_C) merge( input_tape, output_tape, scratch_tape_D) while any records remain on C or D merge( scratch_tape_C, scratch_tape_D, output_tape) merge( scratch_tape_C, scratch_tape_D, input_tape)

    # take the next sorted chunk from the input tapes, and merge into the single given output_tape. # tapes are scanned linearly. # tape[next] gives the record currently under the read head of that tape. # tape[current] gives the record previously under the read head of that tape. # (Generally both tape[current] and tape[previous] are buffered in RAM ...) function merge(left[], right[], output_tape[]) do if left[current] = right[current] append left[current] to output_tape read next record from left tape else append right[current] to output_tape read next record from right tape while left[current] < left[next] and right[current] < right[next] if left[current] < left[next] append current_left_record to output_tape if right[current] < right[next] append current_right_record to output_tape return

    Either form of merge sort can be generalized to any number of tapes.

    Optimizing merge sort

    On modern computers, locality of reference
    Locality of reference

    In computer science, locality of reference, also known as the principle of locality, is the phenomenon of the same value or related computer storage locations being frequently accessed....
     can be of paramount importance in software optimization, because multi-level memory hierarchies
    Memory hierarchy

    The hierarchical arrangement of computer storage in current computer architectures is called the memory hierarchy. It is designed to take advantage of memory locality in computer programs....
     are used. Cache
    Cache

    In computer science, a cache is a collection of data duplicating original values stored elsewhere or computed earlier, where the original data is expensive to fetch or to compute, compared to the cost of reading the 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 single page in memory. 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.

    M.A. Kronrod suggested in 1969 an alternative version of merge sort that used constant additional space.

    Comparison with other sort algorithms

    Although heapsort
    Heapsort

    Heapsort is a comparison sort sorting algorithm, and is part of the selection sort family. Although somewhat slower in practice on most machines than a good implementation of quicksort, it has the advantage of a worst-case big O notation runtime....
     has the same time bounds as merge sort, it requires only T(1) auxiliary space instead of merge sort's T(n), and is often faster in practical implementations. Quicksort
    Quicksort

    Quicksort is a well-known sorting algorithm developed by C. A. R. Hoare that, average performance, makes comparisons to sort n items. However, in the Best, worst and average case, it makes comparisons....
    , however, is considered by many to be the fastest general-purpose sort algorithm. On the plus side, 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
    Linked list

    In computer science, a linked list is one of the fundamental data structures, and can be used to implement other data structures. It consists of a sequence of node s, each containing arbitrary data Field s and one or two reference s pointing to the next and/or previous nodes....
    : in this situation it is relatively easy to implement a merge sort in such a way that it requires only T(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

    In computer programming, Perl is a high-level programming language, List of programming languages by category, Interpreter , dynamic programming language....
     5.8, merge sort is its default sorting algorithm (it was quicksort in previous versions of Perl). In Java, the methods use merge sort or a tuned quicksort depending on the datatypes and for implementation efficiency switch to insertion sort
    Insertion sort

    Insertion sort is a simple sorting algorithm, a comparison sort in which the sorted array is built one entry at a time. It is much less efficient on large lists than more advanced algorithms such as quicksort, heapsort, or merge sort....
     when fewer than seven array elements are being sorted.[https://openjdk.dev.java.net/source/browse/openjdk/jdk/trunk/jdk/src/share/classes/java/util/Arrays.java?view=markup]

    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 (see online algorithm
    Online algorithm

    In computer science, an online algorithm is one that can process its input piece-by-piece in a serial fashion, i.e. in the order that the input is fed to the algorithm, without having the entire input available from the start....
    ). 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 store the list in a self-balancing binary search tree
    Self-balancing binary search tree

    In computer science, a self-balancing binary search tree or height-balanced binary search tree is a binary search tree that attempts to keep its height, or the number of levels of nodes beneath the root, as small as possible at all times, automatically....
     and add elements to it as they are received.

    Citations and notes



    General


    External links


    • – graphical demonstration and discussion of array-based merge sort
    • with level order
      Tree traversal

      In computer science, tree-traversal refers to the process of visiting each node in a tree data structure, exactly once, in a systematic way. Such traversals are classified by the order in which the nodes are visited....
       recursive calls to help improve algorithm analysis
    • on LiteratePrograms
    • which allows experimentation with initial state and shows statistics]