Merge sort
From CodeCodex
| Related content: |
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.
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.
Contents |
[edit] Implementations
[edit] Pseudocode
function mergesort(m)
var list left, right
if length(m) ≤ 1
return m
else
middle = length(m) / 2
for each x in m up to middle
add x to left
for each x in m after middle
add x to right
left = mergesort(left)
right = mergesort(right)
result = merge(left, right)
return result
There are several variants for the merge() function, the simplest variant could look like this:
function merge(left,right)
var list result
while 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)
if length(left) > 0
append left to result
if length(right) > 0
append right to result
return result
[edit] Ada
Ada implementation uses type Data_T for the data array.
function Mergesort (Data : in Data_T) return Data_T is
begin
if Data'Length <= 1 then
return Data;
else
declare
Middle : Integer := (Data'First + Data'Last) / 2;
Left : Data_T := Data (Data'First .. Middle);
Right : Data_T := Data (Middle + 1 .. Data'Last);
begin
Left := Mergesort (Left);
Right := Mergesort (Right);
return Merge(Left, Right);
end;
end if;
end Mergesort;
Definition of the Merge function:
function Merge (Left : Data_T; Right : Data_T) return Data_T is
Result : Data_T (1 .. Left'Length + Right'Length);
L : Integer := Left'First;
R : Integer := Right'First;
I : Integer := Result'First;
begin
while L <= Left'Last and R <= Right'Last loop
if Left(L) <= Right(R) then
Result(I) := Left(L);
L := L + 1;
I := I + 1;
else
Result(I) := Right(R);
R := R + 1;
I := I + 1;
end if;
end loop;
if L <= Left'Last then
Result(I..Result'Last) := Left(L..Left'Last);
end if;
if R <= Right'Last then
Result(I..Result'Last) := Right(R..Right'Last);
end if;
return Result;
end Merge;
[edit] 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);
}
[edit] 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
[edit] 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;
// if the array has an odd number of elements, let the second half take the extra one
// see note (1)
int elementsInA2 = array.length - elementsInA1;
// 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 or equal to 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 arr2 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
[edit] Common Lisp
;;; Helper function to tell us if a given sequence has just one element.
(defun single (sequence)
(if (consp sequence)
(not (cdr sequence))
(= (length sequence) 1)))
;;; Sequence can be a vector or a list. Note that this means that this
;;; code isn't optimized for any of those.
(defun merge-sort (sequence)
(if (or (null sequence) (single sequence))
sequence
(let ((half (truncate (/ (length sequence) 2))))
;; MERGE is a standard common-lisp function, which does just
;; what we want.
(merge (type-of sequence)
(merge-sort (subseq sequence 0 half))
(merge-sort (subseq sequence half))
#'<))))
[edit] 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
[edit] 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>
This function is included in the OCaml stdlib as List.merge but is also included here for clarity. Function to halve a list:
# let rec halve = function
| []
| [_] as t1 -> t1, []
| h::t ->
let t1, t2 = halve t in
h::t2, t1
;;
val halve : 'a list -> 'a list * 'a list = <fun>
Function to merge sort a list:
# let rec merge_sort = function
| []
| [_] as list -> list
| list ->
let l1, l2 = halve list in
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]
[edit] Prolog
This is an ISO-Prolog compatible implementation of merge sort with the exception of the predicates append/3 and length/2 which, while not prescribed by the ISO standard, are available in virtually all Prolog implementations.
% Merge-Sort: ms(+Source, ?Result)
ms(Xs, Rs) :-
length(Xs, L),
( L =< 2 ->
Rs = Xs
; Split is L//2,
length(Front0, Split),
append(Front0, Back0, Xs),
ms(Front0, Front),
ms(Back0, Back),
merge(Front, Back, Rs)
).
% Merge of lists: merge(+List1, +List2, -Result)
merge([], Xs, Xs) :- !.
merge(Xs, [], Xs) :- !.
merge([X|Xs], [Y|Ys], Zs) :-
( X @=< Y ->
Zs = [X|Rest],
merge(Xs, [Y|Ys], Rest)
; Zs = [Y|Rest],
merge([X|Xs], Ys, Rest)
).
[edit] Python
def sort(array):
if len(array) <= 1: return array
mid = len(array) // 2
return merge (sort(array[0:mid]), sort(array[mid:]))
# this may not be the most thoroughly idiomatic python, or the
# most efficient merge (it duplicates data when "Transmitting")
# but it works
def merge(left, right):
merged = []
i = 0
j = 0
while len(merged) < len(left)+len(right):
if left[i] <= right[j]:
merged.append(left[i])
i += 1
if i == len(left):
# Knuth, TaoCP Vol 3 5.2.4 Calls this the "transmit"
merged.extend(right[j:])
break
else:
merged.append(right[j])
j += 1
if j == len(right):
merged.extend(left[i:])
break
return merged
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.append(front.pop(0) if front[0]<=back[0] else back.pop(0))
# add the remaining end
result.extend(front or back)
return result
[edit] 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
[edit] Scheme
(define (loe p1 p2);;implements less than or equal
(<= (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
)
)
)
)
[edit] Seed7
Version without additional storage
const proc: mergeSort (inout array elemType: arr, in var integer: lo, in integer: hi) is func
local
var integer: mid is 0;
var elemType: help is elemType.value;
var integer: k is 0;
begin
if lo < hi then
mid := (lo + hi) div 2;
mergeSort(arr, lo, mid);
mergeSort(arr, succ(mid), hi);
incr(mid);
while lo < mid and mid <= hi do
if arr[lo] <= arr[mid] then
incr(lo);
else
help := arr[mid];
for k range mid downto succ(lo) do
arr[k] := arr[pred(k)];
end for;
arr[lo] := help;
incr(lo);
incr(mid);
end if;
end while;
end if;
end func;
const proc: mergeSort (inout array elemType: arr) is func
begin
mergeSort(arr, 1, length(arr));
end func;
Original source: [1]
Version with additional storage
const proc: mergeSort2 (inout array elemType: arr, in integer: lo, in integer: hi, inout array elemType: scratch) is func
local
var integer: mid is 0;
var integer: k is 0;
var integer: t_lo is 0;
var integer: t_hi is 0;
begin
if lo < hi then
mid := (lo + hi) div 2;
mergeSort2(arr, lo, mid, scratch);
mergeSort2(arr, succ(mid), hi, scratch);
t_lo := lo;
t_hi := succ(mid);
for k range lo to hi do
if t_lo <= mid and (t_hi > hi or arr[t_lo] < arr[t_hi]) then
scratch[k] := arr[t_lo];
incr(t_lo);
else
scratch[k] := arr[t_hi];
incr(t_hi);
end if;
end for;
for k range lo to hi do
arr[k] := scratch[k];
end for;
end if;
end func;
const proc: mergeSort2 (inout array elemType: arr) is func
local
var array elemType: scratch is 0 times elemType.value;
begin
scratch := length(arr) times elemType.value;
mergeSort2(arr, 1, length(arr), scratch);
end func;
Original source: [2]
[edit] Fortran
subroutine Merge(A,NA,B,NB,C,NC) integer, intent(in) :: NA,NB,NC ! Normal usage: NA+NB = NC integer, intent(in out) :: A(NA) ! B overlays C(NA+1:NC) integer, intent(in) :: B(NB) integer, intent(in out) :: C(NC) integer :: I,J,K I = 1; J = 1; K = 1; do while(I <= NA .and. J <= NB) if (A(I) <= B(J)) then C(K) = A(I) I = I+1 else C(K) = B(J) J = J+1 endif K = K + 1 enddo do while (I <= NA) C(K) = A(I) I = I + 1 K = K + 1 enddo return end subroutine merge recursive subroutine MergeSort(A,N,T) integer, intent(in) :: N integer, dimension(N), intent(in out) :: A integer, dimension((N+1)/2), intent (out) :: T integer :: NA,NB,V if (N < 2) return if (N == 2) then if (A(1) > A(2)) then V = A(1) A(1) = A(2) A(2) = V endif return endif NA=(N+1)/2 NB=N-NA call MergeSort(A,NA,T) call MergeSort(A(NA+1),NB,T) if (A(NA) > A(NA+1)) then T(1:NA)=A(1:NA) call Merge(T,NA,A(NA+1),NB,A,N) endif return end subroutine MergeSort program TestMergeSort integer, parameter :: N = 8 integer, dimension(N) :: A = (/ 1, 5, 2, 7, 3, 9, 4, 6 /) integer, dimension ((N+1)/2) :: T call MergeSort(A,N,T) write(*,'(A,/,10I3)')'Sorted array :',A end program TestMergeSort
[edit] JavaScript
function mergeSort() {
if(this.length > 1) {
var firstHalf = Math.floor(this.length / 2);
var secondHalf = this.length - firstHalf;
var arr1 = new Array(firstHalf);
var arr2 = new Array(secondHalf);
for(var i = 0; i < firstHalf; i++) {
arr1[i] = this[i];
}
for(i = firstHalf; i < firstHalf + secondHalf; i++) {
arr2[i - firstHalf] = this[i];
}
arr1.mergeSort();
arr2.mergeSort();
var i=0;
var j=0;
var k=0;
while(arr1.length != j && arr2.length != k) {
if(arr1[j] <= arr2[k]) {
this[i] = arr1[j];
i++;
j++;
} else {
this[i] = arr2[k];
i++;
k++;
}
}
while(arr1.length != j) {
this[i] = arr1[j];
i++;
j++;
}
while(arr2.length != k) {
this[i] = arr2[k];
i++;
k++;
}
}
}
Array.prototype.mergeSort = mergeSort;
[edit] 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) = 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, 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/(2k +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 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, 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.
[edit] 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.
[edit] 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.
[edit] 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. 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.
[edit] 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

