# Merge sort

### From CodeCodex

In computer science, **merge sort** or **mergesort** is a sorting algorithm for rearranging lists (or any other data structure that can only be accessed sequentially, e.g. file streams) into a specified order. It is a particularly good example of the divide and conquer algorithmic paradigm. It is a comparison sort.

## Contents

## Algorithm

Conceptually, merge sort works as follows:

- Divide the unsorted list into two sublists of about half the size
- Sort each of the two sublists
- Merge the two sorted sublists back into one sorted list.

The algorithm was invented by John von Neumann in 1945.

## Implementations

### Pseudocode

functionmergesort(m)varlistleft, rightiflength(m) ≤ 1returnmelsemiddle = length(m) / 2for eachxinmup tomiddle add x to leftfor eachxinmaftermiddle add x to right left = mergesort(left) right = mergesort(right) result = merge(left, right)returnresult

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

functionmerge(left,right)varlistresultwhilelength(left) > 0andlength(right) > 0iffirst(left) ≤ first(right) append first(left) to result left = rest(left)elseappend first(right) to result right = rest(right)iflength(left) > 0 append left to resultiflength(right) > 0 append right to resultreturnresult

### Java

public int[] mergeSort(int array[]) // pre: array is full, all elements are valid integers (not null) // post: array is sorted in ascending order (lowest to highest) { // if the array has more than 1 element, we need to split it and merge the sorted halves if(array.length > 1) { // number of elements in sub-array 1 // if odd, sub-array 1 has the smaller half of the elements // e.g. if 7 elements total, sub-array 1 will have 3, and sub-array 2 will have 4 int elementsInA1 = array.length/2; // since we want an even split, we initialize the length of sub-array 2 to // equal the length of sub-array 1 int elementsInA2 = elementsInA1; // if the array has an odd number of elements, let the second half take the extra one // see note (1) if((array.length % 2) == 1) elementsInA2 += 1; // declare and initialize the two arrays once we've determined their sizes int arr1[] = new int[elementsInA1]; int arr2[] = new int[elementsInA2]; // copy the first part of 'array' into 'arr1', causing arr1 to become full for(int i = 0; i < elementsInA1; i++) arr1[i] = array[i]; // copy the remaining elements of 'array' into 'arr2', causing arr2 to become full for(int i = elementsInA1; i < elementsInA1 + elementsInA2; i++) arr2[i - elementsInA1] = array[i]; // recursively call mergeSort on each of the two sub-arrays that we've just created // note: when mergeSort returns, arr1 and arr2 will both be sorted! // it's not magic, the merging is done below, that's how mergesort works :) arr1 = mergeSort(arr1); arr2 = mergeSort(arr2); // the three variables below are indexes that we'll need for merging // [i] stores the index of the main array. it will be used to let us // know where to place the smallest element from the two sub-arrays. // [j] stores the index of which element from arr1 is currently being compared // [k] stores the index of which element from arr2 is currently being compared int i = 0, j = 0, k = 0; // the below loop will run until one of the sub-arrays becomes empty // in my implementation, it means until the index equals the length of the sub-array while(arr1.length != j && arr2.length != k) { // if the current element of arr1 is less than current element of arr2 if(arr1[j] < arr2[k]) { // copy the current element of arr1 into the final array array[i] = arr1[j]; // increase the index of the final array to avoid replacing the element // which we've just added i++; // increase the index of arr1 to avoid comparing the element // which we've just added j++; } // if the current element of arr2 is less than current element of arr1 else { // copy the current element of arr1 into the final array array[i] = arr2[k]; // increase the index of the final array to avoid replacing the element // which we've just added i++; // increase the index of arr2 to avoid comparing the element // which we've just added k++; } } // at this point, one of the sub-arrays has been exhausted and there are no more // elements in it to compare. this means that all the elements in the remaining // array are the highest (and sorted), so it's safe to copy them all into the // final array. while(arr1.length != j) { array[i] = arr1[j]; i++; j++; } while(arr2.length != k) { array[i] = arr2[k]; i++; k++; } } // return the sorted array to the caller of the function return array; }

Source:MyCSResource.net

### C

// Mix two sorted tables in one and split the result into these two tables. int *Mix(int *tab1,int *tab2,int count1,int count2) { int i,i1,i2; i = i1 = i2 = 0; int * temp = (int *)malloc(sizeof(int)*(count1+count2)); while((i1<count1) && (i2<count2)) { while((i1<count1) && (*(tab1+i1)<=*(tab2+i2))) { *(temp+i++) = *(tab1+i1); i1++; } if (i1<count1) { while((i2<count2) && (*(tab2+i2)<=*(tab1+i1))) { *(temp+i++) = *(tab2+i2); i2++; } } } memcpy(temp+i,tab1+i1,(count1-i1)*sizeof(int)); memcpy(tab1,temp,count1*sizeof(int)); memcpy(temp+i,tab2+i2,(count2-i2)*sizeof(int)); memcpy(tab2,temp+count1,count2*sizeof(int)); // These two lines can be: // memcpy(tab2,temp+count1,i2*sizeof(int)); free(temp); } // MergeSort a table of integer of size count. // Never tested. void MergeSort(int *tab,int count) { if (count==1) return; MergeSort(tab,count/2); MergeSort(tab+count/2,(count+1)/2); Mix(tab,tab+count/2,count/2,(count+1)/2); }

### Scheme

(define (loe p1 p2);;implements less than or equal (or (< (cdr p1) (cdr p2)) (= (cdr p1) (cdr p2)))) (define (mergesort L) (cond ((= (length L) 0) '()) ((= (length L) 1) L); the 1 element list is sorted ((= (length L) 2) (if (< (cdar L) (cdar (cdr L))) L (list (car (cdr L)) (car L));;special case for len 2 list ) ) (else (mergelist (mergesort (firstn L (/ (length L) 2))) (mergesort (lastn L (/ (length L) 2))) );;recursively call mergesort on both halves ) ) ) (define (firstn L N) ;;pre: N not bigger than size of L (cond ((= N 0) '()) ((or (= N 1) (< N 2)) (list (car L))) (else (cons (car L) (firstn (cdr L) (- N 1)))) ) ) (define (lastn L N) ;;pre: N not bigger than size of L (cond ((= N 0) L) ((or(= N 1) (< N 2)) (cdr L)) (else (lastn (cdr L) (- N 1))) ) ) (define (mergelist primero segundo) ;;;pre: primero and segundo are lists sorted in increasing order ;;;post: returns a single sorted list containing the elements of primero and segundo (cond ((null? primero) segundo);;first base case ((null? segundo) primero);;second base case ((loe (car primero) (car segundo)) (cons (car primero) (mergelist (cdr primero) segundo);;first main case )) ((> (cdar primero) (cdar segundo)) (cons (car segundo) (mergelist primero (cdr segundo));;second main case ) ) ) )

### Haskell

sort :: Ord a => [a] -> [a] sort [] = [] sort [x] = [x] sort xs = merge (sort ys) (sort zs) where (ys,zs) = splitAt (length xs `div` 2) xs merge [] y=y merge x []=x merge (x:xs) (y:ys) | x<y = x:merge xs (y:ys) | otherwise = y:merge (x:xs) ys

### OCaml

Function to merge a pair of sorted lists:

# let rec merge = function | list, [] | [], list -> list | h1::t1, h2::t2 -> if h1<h2 then h1::merge(t1, h2::t2) else h2::merge(h1::t1, t2);; val merge : 'a list * 'a list -> 'a list = <fun>

Function to halve a list:

# let rec halve = function | [] | [_] as t2 -> [], t2 | h1::h2::t -> match halve t with t1, t2 -> h1::t1, h2::t2;; val halve : 'a list -> 'a list * 'a list = <fun>

Function to merge sort a list:

# let rec merge_sort = function | [] | [_] as list -> list | list -> match halve list with | l1, l2 -> merge(merge_sort l1, merge_sort l2);; val sort : 'a list -> 'a list = <fun>

For example:

# merge_sort [6; 7; 0; 8; 3; 2; 4; 9; 5; 1];; - : int list = [0; 1; 2; 3; 4; 5; 6; 7; 8; 9]

### Prolog

This is an ISO-Prolog compatible implementation of merge sort with the exception of the predicate append(-list, -list, -list), which is available in most Prolog implementations. Special prolog dialects might provide some of the predicates used in this implementation.

% Merge-Sort: ms(<source>, <result>) % ms([], []). ms(Xs, Rs) :- len(Xs, L), ms(Xs, Rs, L), !. % Merge-Sort: ms(<source>, <result>, len). Here len is the number of elements in <source> which will be sorted % ms([], [], _). ms(Xs, Xs, 0) :- !. ms(Xs, Xs, 1) :- !. ms(Xs, Ys, N) :- N > 1, N1 is N//2, N2 is N-N1, split(Xs, XAs, XBs, XCs, N1, N), ms(XAs, XAMs, N1), ms(XBs, XBMs, N2), merge(XAMs, XBMs, Yss), append(Yss, XCs, Ys), !. % Merge of lists: merge(<list1>, <list2>, <result>) % merge([], Xs, Xs). merge(Xs, [], Xs). merge([X|Xs], [Y|Ys], Zs) :- X =< Y -> (merge(Xs, [Y|Ys], Zss), append([X], Zss, Zs), !); (merge([X|Xs], Ys, Zss), append([Y], Zss, Zs), !). % Splits a list into three chunks at the positions given. Positions need not be within the bounds of the list % split([], [], [], [], _, _). split(Xs, [], [], Xs, 0, 0). split(Xs, [], As, Bs, 0, N) :- 0 =< N, split(Xs, As, Bs, N), !. split(Xs, As, [], Bs, N, N) :- 0 =< N, split(Xs, As, Bs, N), !. split(Xs, As, Bs, Cs, N, M) :- 0 < N, N =< M, Xs = [X|Xss], As = [X|Ass], N1 is N-1, M1 is M-1, split(Xss, Ass, Bs, Cs, N1, M1), !. % Length of a list % len([], 0). len([_|Xs], N) :- len(Xs, N1), N is N1+1.

The above implementation assumes that comparison is done with the '=<' operator. Instead, one can pass in a rule for comparing list entries. Evaluation might then be effected as follows:

% comp(+functor, +atomic, + atomic, -integer): Compares atomic values % functor: A 3-arguent predicate; this predicate implements the comparison % atomic : Atomic values % integer: Result, interpreted according to sign comp(F, X, Y, I) :- functor(F, N, 3), arg(1, F, X), arg(2, F, Y), arg(3, F, I), call(F).

### Python

def sort(array): if len(array) <= 1: return array mid = len(array) // 2 return merge (sort(array[0:mid]), sort(array[mid:]))

### Ruby

def mergesort(list)
return list if list.size <= 1
mid = list.size / 2
left = list[0, mid]
right = list[mid, list.size]
merge(mergesort(left), mergesort(right))
end
def merge(left, right)
sorted = []
until left.empty? or right.empty?
if left.first <= right.first
sorted << left.shift
else
sorted << right.shift
end
end
sorted.concat(left).concat(right)
end

Full implementation:

def mergesort(n): """Recursively merge sort a list. Returns the sorted list.""" front = n[:len(n)/2] back = n[len(n)/2:] if len(front) > 1: front = mergesort(front) if len(back) > 1: back = mergesort(back) return merge(front, back) def merge(front, back): """Merge two sorted lists together. Returns the merged list.""" result = [] while front and back: # pick the smaller one from the front and stick it on result += front[0]<back[0] and [front.pop(0)] or [back.pop(0)] # add the remaining end result += front or back return result

### Miranda

sort [] = [] sort [x] = [x] sort array = merge (sort left) (sort right) where left = [array!y | y <- [0..mid]] right = [array!y | y <- [(mid+1)..max]] max = #array - 1 mid = max div 2

## Analysis

In sorting *n* items, 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*) = 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.

In the worst case, merge sort does exactly (*n* ⌈log *n*⌉ - 2^{⌈log n⌉} + 1) comparisons, which is between (*n* log *n* - *n* + 1) and

(*n* log *n* - 0.9139·*n* + 1) [logs are base 2]. Note, 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.

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 α = -1 + ∑ 1/(2^{k} +1), *k* = 0 → ∞, α ≈ 0.2645.

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.

Recursive implementations of merge sort make 2*n* - 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, meaning memory the size of the input must be allocated for the sorted output to be stored in. Sorting in-place is possible but requires an extremely complicated implementation and hurts performance.

Merge sort is much more efficient than quicksort 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 (inefficient) implementations of quicksort, merge sort is a stable sort as long as the merge operation is implemented properly.

## Optimizing merge sort

This might seem to be of historical interest only, but on modern computers, locality of reference is of paramount importance in software optimization, because multi-level memory hierarchies are used. In some sense, main RAM can be seen as a fast tape drive, level 3 cache memory as a slightly faster one, level 2 cache memory as faster still, and so on. In some circumstances, cache reloading might impose unacceptable overhead and a carefully crafted merge sort might result in a significant improvement in running time. This opportunity might change if fast memory becomes very cheap again, or if exotic architectures like the Tera MTA become commonplace.

Designing a merge sort to perform optimally often requires adjustment to available hardware, eg. number of tape drives, or size and speed of the relevant cache memory levels.

## Comparison with other sort algorithms

Although heap sort has the same time bounds as merge sort, it requires only Ω(1) auxiliary space instead of merge sort's Ω(n), and is consequently often faster in practical implementations. Quicksort, however, is considered by many to be the fastest general-purpose sort algorithm in practice. Its average-case complexity is O(*n* log *n*), with a much smaller coefficient, in good implementations, than merge sort's, even though it is quadratic in the worst case. 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: in this situation it is relatively easy to implement a merge sort in such a way that it does not require Ω(n) auxiliary space (instead only Ω(1)), and the slow random-access performance of a linked list makes some other algorithms (such as quick sort) 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 mergesort and a tuned quicksort depending on the datatypes.

## Utility in online sorting

Mergesort'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). 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 and add elements to it as they are received.

## References

- Donald Knuth.
*The Art of Computer Programming*, Volume 3:*Sorting and Searching*, Second Edition. Addison-Wesley, 1998. ISBN 0-201-89685-0. Section 5.2.4: Sorting by Merging, pp.158–168. - Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein.
*Introduction to Algorithms*, Second Edition. MIT Press and McGraw-Hill, 2001. ISBN 0262032937. Section 2.3: Designing algorithms, pp.27–37.

## External links

- Dictionary of Algorithms and Data Structures: Merge sort
- Merge Sort Algorithm Simulation
- Mergesort For Linked Lists
- Merge Sort Tutorial with diagrams and Java code