<?xml version="1.0"?>
<feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en">
	<id>https://en.formulasearchengine.com/index.php?action=history&amp;feed=atom&amp;title=Mutual_recursion</id>
	<title>Mutual recursion - Revision history</title>
	<link rel="self" type="application/atom+xml" href="https://en.formulasearchengine.com/index.php?action=history&amp;feed=atom&amp;title=Mutual_recursion"/>
	<link rel="alternate" type="text/html" href="https://en.formulasearchengine.com/index.php?title=Mutual_recursion&amp;action=history"/>
	<updated>2026-04-04T00:30:22Z</updated>
	<subtitle>Revision history for this page on the wiki</subtitle>
	<generator>MediaWiki 1.43.0-wmf.28</generator>
	<entry>
		<id>https://en.formulasearchengine.com/index.php?title=Mutual_recursion&amp;diff=284548&amp;oldid=prev</id>
		<title>en&gt;Ldionne92: Add missing braces to C function definition.</title>
		<link rel="alternate" type="text/html" href="https://en.formulasearchengine.com/index.php?title=Mutual_recursion&amp;diff=284548&amp;oldid=prev"/>
		<updated>2014-03-21T23:29:37Z</updated>

		<summary type="html">&lt;p&gt;Add missing braces to C function definition.&lt;/p&gt;
&lt;a href=&quot;https://en.formulasearchengine.com/index.php?title=Mutual_recursion&amp;amp;diff=284548&amp;amp;oldid=284547&quot;&gt;Show changes&lt;/a&gt;</summary>
		<author><name>en&gt;Ldionne92</name></author>
	</entry>
	<entry>
		<id>https://en.formulasearchengine.com/index.php?title=Mutual_recursion&amp;diff=284547&amp;oldid=prev</id>
		<title>67.169.93.106: /* Computer functions */</title>
		<link rel="alternate" type="text/html" href="https://en.formulasearchengine.com/index.php?title=Mutual_recursion&amp;diff=284547&amp;oldid=prev"/>
		<updated>2014-02-17T11:05:57Z</updated>

		<summary type="html">&lt;p&gt;&lt;span class=&quot;autocomment&quot;&gt;Computer functions&lt;/span&gt;&lt;/p&gt;
&lt;a href=&quot;https://en.formulasearchengine.com/index.php?title=Mutual_recursion&amp;amp;diff=284547&amp;amp;oldid=659&quot;&gt;Show changes&lt;/a&gt;</summary>
		<author><name>67.169.93.106</name></author>
	</entry>
	<entry>
		<id>https://en.formulasearchengine.com/index.php?title=Mutual_recursion&amp;diff=659&amp;oldid=prev</id>
		<title>en&gt;Nbarth: /* Data types */ wording</title>
		<link rel="alternate" type="text/html" href="https://en.formulasearchengine.com/index.php?title=Mutual_recursion&amp;diff=659&amp;oldid=prev"/>
		<updated>2014-01-25T07:27:48Z</updated>

		<summary type="html">&lt;p&gt;&lt;span class=&quot;autocomment&quot;&gt;Data types: &lt;/span&gt; wording&lt;/p&gt;
&lt;p&gt;&lt;b&gt;New page&lt;/b&gt;&lt;/p&gt;&lt;div&gt;{{Infobox Algorithm&lt;br /&gt;
|class=[[Sorting algorithm]]&lt;br /&gt;
|image=[[File:Merge-sort-example-300px.gif]]&lt;br /&gt;
|caption=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.&lt;br /&gt;
|data=[[Array data structure|Array]]&lt;br /&gt;
|time=O(&amp;#039;&amp;#039;n&amp;#039;&amp;#039; log &amp;#039;&amp;#039;n&amp;#039;&amp;#039;)&lt;br /&gt;
|best-time=O(&amp;#039;&amp;#039;n&amp;#039;&amp;#039; log &amp;#039;&amp;#039;n&amp;#039;&amp;#039;) typical,&lt;br /&gt;
O(&amp;#039;&amp;#039;n&amp;#039;&amp;#039;) natural variant&lt;br /&gt;
|average-time=O(&amp;#039;&amp;#039;n&amp;#039;&amp;#039; log &amp;#039;&amp;#039;n&amp;#039;&amp;#039;)&lt;br /&gt;
|space=O(&amp;#039;&amp;#039;n&amp;#039;&amp;#039;) auxiliary&lt;br /&gt;
|optimal=Yes&lt;br /&gt;
}}&lt;br /&gt;
[[Image:Merge sort animation2.gif|right|thumb|Merge sort animation. The sorted elements are represented by dots.]]&lt;br /&gt;
In [[computer science]], a &amp;#039;&amp;#039;&amp;#039;merge sort&amp;#039;&amp;#039;&amp;#039; (also commonly spelled &amp;#039;&amp;#039;&amp;#039;mergesort&amp;#039;&amp;#039;&amp;#039;) is an &amp;#039;&amp;#039;[[Big O notation|O]]&amp;#039;&amp;#039;(&amp;#039;&amp;#039;n&amp;#039;&amp;#039; log &amp;#039;&amp;#039;n&amp;#039;&amp;#039;) [[comparison sort|comparison-based]] [[sorting algorithm]]. Most implementations produce a [[Sorting algorithm#Stability|stable sort]], which means that the implementation preserves the input order of equal elements in the sorted output. Mergesort is a [[divide and conquer algorithm]] that was invented by [[John von Neumann]] in 1945.&amp;lt;ref&amp;gt;{{Harvtxt|Knuth|1998|p=158}}&amp;lt;/ref&amp;gt; A detailed description and analysis of bottom-up mergesort appeared in a report by [[Herman Goldstine|Goldstine]] and Neumann as early as 1948.&amp;lt;ref&amp;gt;{{cite journal |title=A meticulous analysis of mergesort programs |year=1997 |author=Jyrki Katajainen and Jesper Larsson Träff |ref=harv}}&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Algorithm==&lt;br /&gt;
Conceptually, a merge sort works as follows&lt;br /&gt;
#Divide the unsorted list into &amp;#039;&amp;#039;n&amp;#039;&amp;#039; sublists, each containing 1 element (a list of 1 element is considered sorted).&lt;br /&gt;
#Repeatedly [[Merge algorithm|merge]] sublists to produce new sorted sublists until there is only 1 sublist remaining.  This will be the sorted list.&lt;br /&gt;
&lt;br /&gt;
===Top-down implementation ===&lt;br /&gt;
Example C like code using indices for top down merge sort algorithm that recursively splits the list (called &amp;#039;&amp;#039;runs&amp;#039;&amp;#039; in this example) into sublists until sublist size is 1, then merges those sublists to produce a sorted list. The copy back step could be avoided if the recursion alternated between two functions so that the direction of the merge corresponds with the level of recursion.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;C&amp;quot;&amp;gt;&lt;br /&gt;
TopDownMergeSort(A[], B[], n)&lt;br /&gt;
{&lt;br /&gt;
    TopDownSplitMerge(A, 0, n, B);&lt;br /&gt;
}&lt;br /&gt;
CopyArray(B[], iBegin, iEnd, A[])&lt;br /&gt;
{&lt;br /&gt;
    for(k = iBegin; k &amp;lt; iEnd; k++)&lt;br /&gt;
        A[k] = B[k];&lt;br /&gt;
}&lt;br /&gt;
TopDownSplitMerge(A[], iBegin, iEnd, B[])&lt;br /&gt;
{&lt;br /&gt;
    if(iEnd - iBegin &amp;lt; 2)                       // if run size == 1&lt;br /&gt;
        return;                                 //   consider it sorted&lt;br /&gt;
    // recursively split runs into two halves until run size == 1,&lt;br /&gt;
    // then merge them and return back up the call chain&lt;br /&gt;
    iMiddle = (iEnd + iBegin) / 2;              // iMiddle = mid point&lt;br /&gt;
    TopDownSplitMerge(A, iBegin,  iMiddle, B);  // split / merge left  half&lt;br /&gt;
    TopDownSplitMerge(A, iMiddle, iEnd,    B);  // split / merge right half&lt;br /&gt;
    TopDownMerge(A, iBegin, iMiddle, iEnd, B);  // merge the two half runs&lt;br /&gt;
    CopyArray(B, iBegin, iEnd, A);              // copy the merged runs back to A&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
TopDownMerge(A[], iBegin, iMiddle, iEnd, B[])&lt;br /&gt;
{&lt;br /&gt;
    i0 = iBegin, i1 = iMiddle;&lt;br /&gt;
    &lt;br /&gt;
    // While there are elements in the left or right runs&lt;br /&gt;
    for (j = iBegin; j &amp;lt; iEnd; j++) {&lt;br /&gt;
        // If left run head exists and is &amp;lt;= existing right run head.&lt;br /&gt;
        if (i0 &amp;lt; iMiddle &amp;amp;&amp;amp; (i1 &amp;gt;= iEnd || A[i0] &amp;lt;= A[i1]))&lt;br /&gt;
            B[j] = A[i0++];  // Increment i0 after using it as an index.&lt;br /&gt;
        else&lt;br /&gt;
            B[j] = A[i1++];  // Increment i1 after using it as an index.&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Bottom-up implementation===&lt;br /&gt;
&lt;br /&gt;
Example code for C using indices for bottom up merge sort algorithm which treats the list as an array of &amp;#039;&amp;#039;n&amp;#039;&amp;#039; sublists (called &amp;#039;&amp;#039;runs&amp;#039;&amp;#039; in this example) of size 1, and iteratively merges sub-lists back and forth between two buffers:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source lang=&amp;quot;C&amp;quot;&amp;gt;&lt;br /&gt;
/* array A[] has the items to sort; array B[] is a work array */&lt;br /&gt;
BottomUpSort(int n, int A[], int B[])&lt;br /&gt;
{&lt;br /&gt;
  int width;&lt;br /&gt;
&lt;br /&gt;
  /* Each 1-element run in A is already &amp;quot;sorted&amp;quot;. */&lt;br /&gt;
&lt;br /&gt;
  /* Make successively longer sorted runs of length 2, 4, 8, 16... until whole array is sorted. */&lt;br /&gt;
  for (width = 1; width &amp;lt; n; width = 2 * width)&lt;br /&gt;
    {&lt;br /&gt;
      int i;&lt;br /&gt;
&lt;br /&gt;
      /* Array A is full of runs of length width. */&lt;br /&gt;
      for (i = 0; i &amp;lt; n; i = i + 2 * width)&lt;br /&gt;
        {&lt;br /&gt;
          /* Merge two runs: A[i:i+width-1] and A[i+width:i+2*width-1] to B[] */&lt;br /&gt;
          /* or copy A[i:n-1] to B[] ( if(i+width &amp;gt;= n) ) */&lt;br /&gt;
          BottomUpMerge(A, i, min(i+width, n), min(i+2*width, n), B);&lt;br /&gt;
        }&lt;br /&gt;
&lt;br /&gt;
      /* Now work array B is full of runs of length 2*width. */&lt;br /&gt;
      /* Copy array B to array A for next iteration. */&lt;br /&gt;
      /* A more efficient implementation would swap the roles of A and B */&lt;br /&gt;
      CopyArray(A, B, n);&lt;br /&gt;
      /* Now array A is full of runs of length 2*width. */&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
BottomUpMerge(int A[], int iLeft, int iRight, int iEnd, int B[])&lt;br /&gt;
{&lt;br /&gt;
  int i0 = iLeft;&lt;br /&gt;
  int i1 = iRight;&lt;br /&gt;
  int j;&lt;br /&gt;
&lt;br /&gt;
  /* While there are elements in the left or right lists */&lt;br /&gt;
  for (j = iLeft; j &amp;lt; iEnd; j++)&lt;br /&gt;
    {&lt;br /&gt;
      /* If left list head exists and is &amp;lt;= existing right list head */&lt;br /&gt;
      if (i0 &amp;lt; iRight &amp;amp;&amp;amp; (i1 &amp;gt;= iEnd || A[i0] &amp;lt;= A[i1]))&lt;br /&gt;
        {&lt;br /&gt;
          B[j] = A[i0];&lt;br /&gt;
          i0 = i0 + 1;&lt;br /&gt;
        }&lt;br /&gt;
      else&lt;br /&gt;
        {&lt;br /&gt;
          B[j] = A[i1];&lt;br /&gt;
          i1 = i1 + 1;&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Top-down implementation using lists ===&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
 &amp;#039;&amp;#039;&amp;#039;function&amp;#039;&amp;#039;&amp;#039; merge_sort(&amp;#039;&amp;#039;list&amp;#039;&amp;#039; m)&lt;br /&gt;
     // Base case. A list of zero or one elements is sorted, by definition.&lt;br /&gt;
     &amp;#039;&amp;#039;&amp;#039;if&amp;#039;&amp;#039;&amp;#039; length(m) &amp;lt;= 1&lt;br /&gt;
         &amp;#039;&amp;#039;&amp;#039;return&amp;#039;&amp;#039;&amp;#039; m&lt;br /&gt;
 &lt;br /&gt;
     // Recursive case. First, *divide* the list into equal-sized sublists.&lt;br /&gt;
     &amp;#039;&amp;#039;&amp;#039;var&amp;#039;&amp;#039;&amp;#039; &amp;#039;&amp;#039;list&amp;#039;&amp;#039; left, right&lt;br /&gt;
     &amp;#039;&amp;#039;&amp;#039;var&amp;#039;&amp;#039;&amp;#039; &amp;#039;&amp;#039;integer&amp;#039;&amp;#039; middle = length(m) / 2&lt;br /&gt;
     &amp;#039;&amp;#039;&amp;#039;for each&amp;#039;&amp;#039;&amp;#039; x &amp;#039;&amp;#039;&amp;#039;in&amp;#039;&amp;#039;&amp;#039; m &amp;#039;&amp;#039;&amp;#039;before&amp;#039;&amp;#039;&amp;#039; middle&lt;br /&gt;
          add x to left&lt;br /&gt;
     &amp;#039;&amp;#039;&amp;#039;for each&amp;#039;&amp;#039;&amp;#039; x &amp;#039;&amp;#039;&amp;#039;in&amp;#039;&amp;#039;&amp;#039; m &amp;#039;&amp;#039;&amp;#039;after or equal&amp;#039;&amp;#039;&amp;#039; middle&lt;br /&gt;
          add x to right&lt;br /&gt;
 &lt;br /&gt;
     // Recursively sort both sublists.&lt;br /&gt;
     left = merge_sort(left)&lt;br /&gt;
     right = merge_sort(right)&lt;br /&gt;
     // *Conquer*: merge the now-sorted sublists.&lt;br /&gt;
     &amp;#039;&amp;#039;&amp;#039;return&amp;#039;&amp;#039;&amp;#039; merge(left, right)&lt;br /&gt;
&lt;br /&gt;
In this example, the &amp;lt;code&amp;gt;merge&amp;lt;/code&amp;gt; function merges the left and right sublists.&lt;br /&gt;
&lt;br /&gt;
 &amp;#039;&amp;#039;&amp;#039;function&amp;#039;&amp;#039;&amp;#039; merge(left, right)&lt;br /&gt;
     &amp;#039;&amp;#039;// receive the left and right sublist as arguments.&amp;#039;&amp;#039;&lt;br /&gt;
     &amp;#039;&amp;#039;// &amp;#039;result&amp;#039; variable for the merged result of two sublists.&amp;#039;&amp;#039;&lt;br /&gt;
     &amp;#039;&amp;#039;&amp;#039;var&amp;#039;&amp;#039;&amp;#039; &amp;#039;&amp;#039;list&amp;#039;&amp;#039; result&lt;br /&gt;
     &amp;#039;&amp;#039;// assign the element of the sublists to &amp;#039;result&amp;#039; variable until there is no element to merge.&amp;#039;&amp;#039; &lt;br /&gt;
     &amp;#039;&amp;#039;&amp;#039;while&amp;#039;&amp;#039;&amp;#039; length(left) &amp;amp;gt; 0 &amp;#039;&amp;#039;&amp;#039;or&amp;#039;&amp;#039;&amp;#039; length(right) &amp;amp;gt; 0&lt;br /&gt;
         &amp;#039;&amp;#039;&amp;#039;if&amp;#039;&amp;#039;&amp;#039; length(left) &amp;amp;gt; 0 &amp;#039;&amp;#039;&amp;#039;and&amp;#039;&amp;#039;&amp;#039; length(right) &amp;amp;gt; 0&lt;br /&gt;
            &amp;#039;&amp;#039;// compare the first two element, which is the small one, of each two sublists.&amp;#039;&amp;#039;&lt;br /&gt;
             &amp;#039;&amp;#039;&amp;#039;if&amp;#039;&amp;#039;&amp;#039; first(left) &amp;lt;= first(right)&lt;br /&gt;
                 &amp;#039;&amp;#039;// the small element is copied to &amp;#039;result&amp;#039; variable.&amp;#039;&amp;#039;&lt;br /&gt;
                 &amp;#039;&amp;#039;// delete the copied one(a first element) in the sublist.&amp;#039;&amp;#039;&lt;br /&gt;
                 append first(left) to result&lt;br /&gt;
                 left = rest(left)&lt;br /&gt;
             &amp;#039;&amp;#039;&amp;#039;else&amp;#039;&amp;#039;&amp;#039;&lt;br /&gt;
                 &amp;#039;&amp;#039;// same operation as the above(in the right sublist).&amp;#039;&amp;#039;&lt;br /&gt;
                 append first(right) to result&lt;br /&gt;
                 right = rest(right)&lt;br /&gt;
         &amp;#039;&amp;#039;&amp;#039;else if&amp;#039;&amp;#039;&amp;#039; length(left) &amp;amp;gt; 0&lt;br /&gt;
             &amp;#039;&amp;#039;// copy all of remaining elements from the sublist to &amp;#039;result&amp;#039; variable, &lt;br /&gt;
             &amp;#039;&amp;#039;// when there is no more element to compare with.&amp;#039;&amp;#039;&lt;br /&gt;
             append first(left) to result&lt;br /&gt;
             left = rest(left)&lt;br /&gt;
         &amp;#039;&amp;#039;&amp;#039;else if&amp;#039;&amp;#039;&amp;#039; length(right) &amp;amp;gt; 0&lt;br /&gt;
             &amp;#039;&amp;#039;// same operation as the above(in the right sublist).&amp;#039;&amp;#039;&lt;br /&gt;
             append first(right) to result&lt;br /&gt;
             right = rest(right)&lt;br /&gt;
     &amp;#039;&amp;#039;&amp;#039;end while&amp;#039;&amp;#039;&amp;#039;&lt;br /&gt;
     &amp;#039;&amp;#039;// return the result of the merged sublists(or completed one, finally).&amp;#039;&amp;#039;&lt;br /&gt;
     &amp;#039;&amp;#039;// the length of the left and right sublists will grow bigger and bigger, after the next call of this function.&amp;#039;&amp;#039;&lt;br /&gt;
     &amp;#039;&amp;#039;&amp;#039;return&amp;#039;&amp;#039;&amp;#039; result&lt;br /&gt;
&lt;br /&gt;
==Natural merge sort==&lt;br /&gt;
&lt;br /&gt;
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. 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. Example:&lt;br /&gt;
&lt;br /&gt;
 Start       : 3--4--2--1--7--5--8--9--0--6&lt;br /&gt;
 Select runs : 3--4  2  1--7  5--8--9  0--6&lt;br /&gt;
 Merge       : 2--3--4  1--5--7--8--9  0--6&lt;br /&gt;
 Merge       : 1--2--3--4--5--7--8--9  0--6&lt;br /&gt;
 Merge       : 0--1--2--3--4--5--6--7--8--9&lt;br /&gt;
&lt;br /&gt;
==Analysis==&lt;br /&gt;
[[Image:merge sort algorithm diagram.svg|thumb|right|300px|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).]]&lt;br /&gt;
&lt;br /&gt;
In sorting &amp;#039;&amp;#039;n&amp;#039;&amp;#039; objects, merge sort has an [[average performance|average]] and [[worst-case performance]] of [[big O notation|O]](&amp;#039;&amp;#039;n&amp;#039;&amp;#039;&amp;amp;nbsp;log&amp;amp;nbsp;&amp;#039;&amp;#039;n&amp;#039;&amp;#039;). If the running time of merge sort for a list of length &amp;#039;&amp;#039;n&amp;#039;&amp;#039; is &amp;#039;&amp;#039;T&amp;#039;&amp;#039;(&amp;#039;&amp;#039;n&amp;#039;&amp;#039;), then the recurrence &amp;#039;&amp;#039;T&amp;#039;&amp;#039;(&amp;#039;&amp;#039;n&amp;#039;&amp;#039;) = 2&amp;#039;&amp;#039;T&amp;#039;&amp;#039;(&amp;#039;&amp;#039;n&amp;#039;&amp;#039;/2) + &amp;#039;&amp;#039;n&amp;#039;&amp;#039; follows from the definition of the algorithm (apply the algorithm to two lists of half the size of the original list, and add the &amp;#039;&amp;#039;n&amp;#039;&amp;#039; steps taken to merge the resulting two lists). The closed form follows from the [[master theorem]].&lt;br /&gt;
&lt;br /&gt;
In the worst case, the number of comparisons merge sort makes is equal to or slightly smaller than (&amp;#039;&amp;#039;n&amp;#039;&amp;#039;&amp;amp;nbsp;⌈[[Binary logarithm|lg]]&amp;amp;nbsp;&amp;#039;&amp;#039;n&amp;#039;&amp;#039;⌉ - 2&amp;lt;sup&amp;gt;⌈lg&amp;amp;nbsp;&amp;#039;&amp;#039;n&amp;#039;&amp;#039;⌉&amp;lt;/sup&amp;gt; + 1), which is between (&amp;#039;&amp;#039;n&amp;#039;&amp;#039;&amp;amp;nbsp;lg&amp;amp;nbsp;&amp;#039;&amp;#039;n&amp;#039;&amp;#039; - &amp;#039;&amp;#039;n&amp;#039;&amp;#039; + 1) and (&amp;#039;&amp;#039;n&amp;#039;&amp;#039;&amp;amp;nbsp;lg&amp;amp;nbsp;&amp;#039;&amp;#039;n&amp;#039;&amp;#039; + &amp;#039;&amp;#039;n&amp;#039;&amp;#039; + O(lg &amp;#039;&amp;#039;n&amp;#039;&amp;#039;)).&amp;lt;ref&amp;gt;The worst case number given here does not agree with that given in [[Donald Knuth|Knuth]]&amp;#039;s &amp;#039;&amp;#039;[[Art of Computer Programming]], Vol 3&amp;#039;&amp;#039;. The discrepancy is due to Knuth analyzing a variant implementation of merge sort that is slightly sub-optimal&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
For large &amp;#039;&amp;#039;n&amp;#039;&amp;#039; and a randomly ordered input list,  merge sort&amp;#039;s expected (average) number of comparisons approaches &amp;#039;&amp;#039;α&amp;#039;&amp;#039;·&amp;#039;&amp;#039;n&amp;#039;&amp;#039; fewer than the worst case where &amp;lt;math&amp;gt;\alpha = -1 + \sum_{k=0}^\infty \frac1{2^k+1} \approx 0.2645.&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In the &amp;#039;&amp;#039;worst&amp;#039;&amp;#039; case, merge sort does about 39% fewer comparisons than [[quicksort]] does in the &amp;#039;&amp;#039;average&amp;#039;&amp;#039; case.  In terms of moves, merge sort&amp;#039;s worst case complexity is [[big O notation|O]](&amp;#039;&amp;#039;n&amp;#039;&amp;#039;&amp;amp;nbsp;log&amp;amp;nbsp;&amp;#039;&amp;#039;n&amp;#039;&amp;#039;)—the same complexity as quicksort&amp;#039;s best case, and merge sort&amp;#039;s best case takes about half as many iterations as the worst case.{{Citation needed|date=June 2008}}&lt;br /&gt;
&lt;br /&gt;
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 programming language|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.&lt;br /&gt;
&lt;br /&gt;
Merge sort&amp;#039;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 &amp;#039;&amp;#039;n&amp;#039;&amp;#039;/2 extra spaces).&lt;br /&gt;
&lt;br /&gt;
Merge sort also has some demerits. One is its use of 2&amp;#039;&amp;#039;n&amp;#039;&amp;#039; locations; the additional &amp;#039;&amp;#039;n&amp;#039;&amp;#039; 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 &amp;#039;&amp;#039;m&amp;#039;&amp;#039; are first copied into &amp;#039;&amp;#039;left&amp;#039;&amp;#039; and &amp;#039;&amp;#039;right&amp;#039;&amp;#039; and later into the list &amp;#039;&amp;#039;result&amp;#039;&amp;#039; on each invocation of &amp;#039;&amp;#039;merge_sort&amp;#039;&amp;#039; (variable names according to the pseudocode above).&lt;br /&gt;
&lt;br /&gt;
==Variants==&lt;br /&gt;
Variants of merge sort are primarily concerned with reducing the space complexity and the cost of copying.&lt;br /&gt;
&lt;br /&gt;
A simple alternative for reducing the space overhead to &amp;#039;&amp;#039;n&amp;#039;&amp;#039;/2 is to maintain &amp;#039;&amp;#039;left&amp;#039;&amp;#039; and &amp;#039;&amp;#039;right&amp;#039;&amp;#039; as a combined structure, copy only the &amp;#039;&amp;#039;left&amp;#039;&amp;#039; part of &amp;#039;&amp;#039;m&amp;#039;&amp;#039; into temporary space, and to direct the &amp;#039;&amp;#039;merge&amp;#039;&amp;#039; routine to place the merged output into &amp;#039;&amp;#039;m&amp;#039;&amp;#039;. With this version it is better to allocate the temporary space outside the &amp;#039;&amp;#039;merge&amp;#039;&amp;#039; routine, so that only one allocation is needed. The excessive copying mentioned previously is also mitigated, since the last pair of lines before the &amp;#039;&amp;#039;return result&amp;#039;&amp;#039; statement (function &amp;#039;&amp;#039; merge &amp;#039;&amp;#039;in the pseudo code above) become superfluous.&lt;br /&gt;
&lt;br /&gt;
[[In-place]] sorting is possible, and still stable, but is more complicated, and slightly slower, requiring non-linearithmic [[quasilinear time]] O(&amp;#039;&amp;#039;n&amp;#039;&amp;#039;&amp;amp;nbsp;log&amp;lt;sup&amp;gt;2&amp;lt;/sup&amp;gt;&amp;amp;nbsp;&amp;#039;&amp;#039;n&amp;#039;&amp;#039;) One way to sort in-place is to merge the blocks recursively.&amp;lt;ref&amp;gt;[http://h2database.googlecode.com/svn/trunk/h2/src/tools/org/h2/dev/sort/InPlaceStableMergeSort.java A Java implementation of in-place stable merge sort]&amp;lt;/ref&amp;gt; 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 already used by the list representation, but the O(log(&amp;#039;&amp;#039;k&amp;#039;&amp;#039;)) used for the recursion trace.&lt;br /&gt;
&lt;br /&gt;
An alternative to reduce the copying into multiple lists is to associate a new field of information with each key (the elements in &amp;#039;&amp;#039;m&amp;#039;&amp;#039; 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.&lt;br /&gt;
&lt;br /&gt;
==Use with tape drives==&lt;br /&gt;
[[File:IBM 729 Tape Drives.nasa.jpg|thumb|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 729]]s.]]&lt;br /&gt;
An [[External sorting|external]] merge sort is practical to run using [[disk storage|disk]] or [[tape drive|tape]] drives when the data to be sorted is too large to fit into [[primary storage|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. &lt;br /&gt;
&lt;br /&gt;
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|Bottom-up implementation]], using pairs of tape drives instead of arrays in memory. The basic algorithm can be described as follows:&lt;br /&gt;
&lt;br /&gt;
# Merge pairs of records from A; writing two-record sublists alternately to C and D.&lt;br /&gt;
# Merge two-record sublists from C and D into four-record sublists; writing these alternately to A and B.&lt;br /&gt;
# Merge four-record sublists from A and B into eight-record sublists; writing these alternately to C and D&lt;br /&gt;
# Repeat until you have one list containing all the data, sorted --- in log2(&amp;#039;&amp;#039;n&amp;#039;&amp;#039;) passes.&lt;br /&gt;
&lt;br /&gt;
Instead of starting with very short 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 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.&amp;lt;ref&amp;gt;Selection sort. Knuth&amp;#039;s snowplow. Natural merge.&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
A more sophisticated merge sort that optimizes tape (and disk) drive usage is the [[polyphase merge sort]].&lt;br /&gt;
&lt;br /&gt;
==Optimizing merge sort==&lt;br /&gt;
On modern computers, [[locality of reference]] can be of paramount importance in [[software optimization]], because multilevel [[Memory hierarchy|memory hierarchies]] are used. [[Cache (computing)|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&amp;#039;s memory cache, have been proposed. For example, the &amp;#039;&amp;#039;&amp;#039;{{visible anchor|tiled merge sort}}&amp;#039;&amp;#039;&amp;#039; algorithm stops partitioning subarrays when subarrays of size S are reached, where S is the number of data items fitting into a CPU&amp;#039;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 on machines that benefit from cache optimization. {{Harv|LaMarca|Ladner|1997}}&lt;br /&gt;
&lt;br /&gt;
{{Harvtxt|Kronrod|1969}} suggested an alternative version of merge sort that uses constant additional space. This algorithm was later refined. {{Harv|Katajainen|Pasanen|Teuhola|1996}}&lt;br /&gt;
&lt;br /&gt;
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 [[page (computer memory)|pages]] fit into main memory.&lt;br /&gt;
&lt;br /&gt;
==Parallel processing==&lt;br /&gt;
Merge sort parallelizes well due to use of the divide-and-conquer method.  A parallel implementation is shown in pseudo-code in the third edition of Cormen, Leiserson, Rivest, and Stein&amp;#039;s &amp;#039;&amp;#039;Introduction to Algorithms&amp;#039;&amp;#039;.&amp;lt;ref&amp;gt;{{Harvnb|Cormen|Leiserson|Rivest|Stein|2009|p=803}}&amp;lt;/ref&amp;gt;  This algorithm uses a 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.&amp;lt;ref&amp;gt;[http://drdobbs.com/high-performance-computing/229400239 V. J. Duvanenko, &amp;quot;Parallel Merge Sort&amp;quot;, Dr. Dobb&amp;#039;s Journal, March 2011]&amp;lt;/ref&amp;gt; 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 &amp;#039;&amp;#039;O&amp;#039;&amp;#039;(1) merge.&amp;lt;ref&amp;gt;{{Cite journal|first1=Richard|last1=Cole|title=Parallel merge sort|journal=SIAM J. Comput.|volume=17|issue=4|date=August 1988|pages=770–785|doi=10.1137/0217049|ref=harv|postscript=&amp;lt;!-- Bot inserted parameter. Either remove it; or change its value to &amp;quot;.&amp;quot; for the cite to end in a &amp;quot;.&amp;quot;, as necessary. --&amp;gt;{{inconsistent citations}}}}&amp;lt;/ref&amp;gt; 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 &amp;#039;&amp;#039;O&amp;#039;&amp;#039;(log &amp;#039;&amp;#039;n&amp;#039;&amp;#039;) time on a CRCW [[Parallel Random Access Machine|PRAM]] with &amp;#039;&amp;#039;n&amp;#039;&amp;#039; processors by performing partitioning implicitly.&amp;lt;ref&amp;gt;Powers, David M. W. [http://citeseer.ist.psu.edu/327487.html Parallelized Quicksort and Radixsort with Optimal Speedup], &amp;#039;&amp;#039;Proceedings of International Conference on Parallel Computing Technologies&amp;#039;&amp;#039;. [[Novosibirsk]]. 1991.&amp;lt;/ref&amp;gt; Powers&amp;lt;ref&amp;gt; David M. W. Powers, [http://david.wardpowers.info/Research/AI/papers/199501-ACAW-PUPC.pdf Parallel Unification: Practical Complexity], Australasian Computer Architecture Workshop, Flinders University, January 1995&amp;lt;/ref&amp;gt; further shows that a pipelined version of Batcher&amp;#039;s [[Bitonic_sorter|Bitonic Mergesort]] at &amp;#039;&amp;#039;O&amp;#039;&amp;#039;(log&amp;lt;sup&amp;gt;2&amp;lt;/sup&amp;gt;&amp;#039;&amp;#039;n&amp;#039;&amp;#039;) time on a butterfly [[sorting network]] is in practice actually faster than his &amp;#039;&amp;#039;O&amp;#039;&amp;#039;(log &amp;#039;&amp;#039;n&amp;#039;&amp;#039;) sorts on a [[Parallel_Random_Access_Machine|PRAM]], and he provides detailed discussion of the hidden overheads in comparison, radix and parallel sorting.&lt;br /&gt;
&lt;br /&gt;
==Comparison with other sort algorithms==&lt;br /&gt;
Although [[heapsort]] has the same time bounds as merge sort, it requires only  Θ(1) auxiliary space instead of merge sort&amp;#039;s Θ(&amp;#039;&amp;#039;n&amp;#039;&amp;#039;). 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 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.&lt;br /&gt;
&lt;br /&gt;
As of [[Perl]] 5.8, merge sort is its default sorting algorithm (it was quicksort in previous versions of Perl). In [[Java platform|Java]], the [http://docs.oracle.com/javase/6/docs/api/java/util/Arrays.html 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.&amp;lt;ref&amp;gt;[https://openjdk.dev.java.net/source/browse/openjdk/jdk/trunk/jdk/src/share/classes/java/util/Arrays.java?view=markup OpenJDK Subversion]&amp;lt;/ref&amp;gt; [[Python (programming language)|Python]] uses [[timsort]], another tuned hybrid of merge sort and insertion sort, that has become the standard sort algorithm in [[Java 7|Java SE 7]],&amp;lt;ref&amp;gt;{{cite web&lt;br /&gt;
| title = Commit 6804124: Replace &amp;quot;modified mergesort&amp;quot; in java.util.Arrays.sort with timsort&lt;br /&gt;
| url = http://hg.openjdk.java.net/jdk7/tl/jdk/rev/bfd7abda8f79&lt;br /&gt;
| last = jjb&lt;br /&gt;
| work = Java Development Kit 7 Hg repo&lt;br /&gt;
| accessdate = 24 Feb 2011&lt;br /&gt;
}}&amp;lt;/ref&amp;gt; on the [[Android (operating system)|Android platform]],&amp;lt;ref&amp;gt;{{cite web&lt;br /&gt;
| title = Class: java.util.TimSort&amp;lt;T&amp;gt;&lt;br /&gt;
| url = http://www.kiwidoc.com/java/l/x/android/android/5/p/java.util/c/TimSort&lt;br /&gt;
| work = Android JDK 1.5 Documentation&lt;br /&gt;
| accessdate = 24 Feb 2011&lt;br /&gt;
}}{{Dead link|date=June 2013}}&amp;lt;/ref&amp;gt; and in [[GNU Octave]].&amp;lt;ref&amp;gt;{{cite web&lt;br /&gt;
| title = liboctave/util/oct-sort.cc&lt;br /&gt;
| url = http://hg.savannah.gnu.org/hgweb/octave/file/0486a29d780f/liboctave/util/oct-sort.cc&lt;br /&gt;
| work = Mercurial repository of Octave source code&lt;br /&gt;
| accessdate = 18 Feb 2013&lt;br /&gt;
| quote = Code stolen in large part from Python&amp;#039;s, listobject.c, which itself had no license header. However, thanks to Tim Peters for the parts of the code I ripped-off.&lt;br /&gt;
| at = Lines 23-25 of the initial comment block.&lt;br /&gt;
}}&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Utility in online sorting==&lt;br /&gt;
Merge sort&amp;#039;s merge operation is useful in [[online algorithm|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.&lt;br /&gt;
&lt;br /&gt;
==Notes==&lt;br /&gt;
{{reflist|30em}}&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
*{{Introduction to Algorithms|3}}&lt;br /&gt;
*{{Cite news&lt;br /&gt;
 | last1 = Katajainen&lt;br /&gt;
 | first1 = Jyrki&lt;br /&gt;
 | last2 = Pasanen&lt;br /&gt;
 | first2 = Tomi&lt;br /&gt;
 | last3 = Teuhola&lt;br /&gt;
 | first3 = Jukka&lt;br /&gt;
 | year = 1996&lt;br /&gt;
 | title = Practical in-place mergesort&lt;br /&gt;
 | periodical = Nordic Journal of Computing&lt;br /&gt;
 | volume = 3&lt;br /&gt;
 | pages = 27–40&lt;br /&gt;
 | url = http://www.diku.dk/hjemmesider/ansatte/jyrki/Paper/mergesort_NJC.ps&lt;br /&gt;
 | accessdate = 2009-04-04&lt;br /&gt;
 | issn=1236-6064&lt;br /&gt;
 | ref = harv}}. Also [http://citeseer.ist.psu.edu/katajainen96practical.html Practical In-Place Mergesort]. Also [http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.22.8523]&lt;br /&gt;
* {{cite book&lt;br /&gt;
  | last = Knuth&lt;br /&gt;
  | first = Donald&lt;br /&gt;
  | authorlink = Donald Knuth&lt;br /&gt;
  | series = [[The Art of Computer Programming]]&lt;br /&gt;
  | volume= 3&lt;br /&gt;
  | title= Sorting and Searching&lt;br /&gt;
  | edition = 2nd&lt;br /&gt;
  | publisher = Addison-Wesley&lt;br /&gt;
  | year=  1998&lt;br /&gt;
  | chapter = Section 5.2.4: Sorting by Merging&lt;br /&gt;
  | pages = 158–168&lt;br /&gt;
  | isbn = 0-201-89685-0&lt;br /&gt;
  | ref = harv}}&lt;br /&gt;
*{{Cite news&lt;br /&gt;
 | last = Kronrod&lt;br /&gt;
 | first = M. A.&lt;br /&gt;
 | year = 1969&lt;br /&gt;
 | title = Optimal ordering algorithm without operational field&lt;br /&gt;
 | periodical = Soviet Mathematics - Doklady&lt;br /&gt;
 | volume = 10&lt;br /&gt;
 | page = 744&lt;br /&gt;
 | ref = harv}}&lt;br /&gt;
*{{Cite journal&lt;br /&gt;
 |first= A.&lt;br /&gt;
 |last= LaMarca&lt;br /&gt;
 |first2= R. E.&lt;br /&gt;
 |last2= Ladner&lt;br /&gt;
 |title= The influence of caches on the performance of sorting&lt;br /&gt;
 |journal= Proc. 8th Ann. ACM-SIAM Symp. on Discrete Algorithms (SODA97)&lt;br /&gt;
 |year= 1997&lt;br /&gt;
 |pages= 370&amp;amp;ndash;379&lt;br /&gt;
 |ref= harv}}&lt;br /&gt;
* {{cite web&lt;br /&gt;
 | author=Sun Microsystems&lt;br /&gt;
 |title=Arrays API&lt;br /&gt;
 |url=http://java.sun.com/javase/6/docs/api/java/util/Arrays.html&lt;br /&gt;
 |accessdate=2007-11-19 }}&lt;br /&gt;
* {{cite web&lt;br /&gt;
 | author=Sun Microsystems&lt;br /&gt;
 |title=java.util.Arrays.java&lt;br /&gt;
 |url=https://openjdk.dev.java.net/source/browse/openjdk/jdk/trunk/jdk/src/share/classes/java/util/Arrays.java?view=markup&lt;br /&gt;
 |accessdate=2007-11-19 }}&lt;br /&gt;
&lt;br /&gt;
==External links==&lt;br /&gt;
{{wikibooks|Algorithm implementation|Sorting/Merge_sort|Merge sort}}&lt;br /&gt;
* [http://www.sorting-algorithms.com/merge-sort Animated Sorting Algorithms: Merge Sort] –  graphical demonstration and discussion of array-based merge sort&lt;br /&gt;
* [http://www.nist.gov/dads/HTML/mergesort.html Dictionary of Algorithms and Data Structures: Merge sort]&lt;br /&gt;
* [http://www.yorku.ca/sychen/research/sorting/index.html Mergesort applet] with &amp;quot;level-order&amp;quot; recursive calls to help improve algorithm analysis&lt;br /&gt;
* [http://opendatastructures.org/versions/edition-0.1e/ods-java/11_1_Comparison_Based_Sorti.html#SECTION001411000000000000000 Open Data Structures - Section 11.1.1 - Merge Sort]&lt;br /&gt;
&lt;br /&gt;
{{sorting}}&lt;br /&gt;
&lt;br /&gt;
{{DEFAULTSORT:Merge Sort}}&lt;br /&gt;
[[Category:Sorting algorithms]]&lt;br /&gt;
[[Category:Comparison sorts]]&lt;br /&gt;
[[Category:Stable sorts]]&lt;br /&gt;
[[Category:Articles with example pseudocode]]&lt;br /&gt;
[[Category:Online sorts]]&lt;br /&gt;
&lt;br /&gt;
[[no:Sorteringsalgoritme#Flettesortering]]&lt;/div&gt;</summary>
		<author><name>en&gt;Nbarth</name></author>
	</entry>
</feed>