Merge sort

From CodeCodex

Revision as of 00:34, 30 May 2007 by (Talk)

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:

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

The algorithm was invented by John von Neumann in 1945.



function mergesort(m)
    var list left, right
    if length(m) ≤ 1
        return m
        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)
            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


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
				// increase the index of arr1 to avoid comparing the element
				// which we've just added
			// if the current element of arr2 is less than current element of arr1
				// 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
				// increase the index of arr2 to avoid comparing the element
				// which we've just added
		// 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];
		while(arr2.length != k)
			array[i] = arr2[k];
	// return the sorted array to the caller of the function
	return array;


// 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);
    if (i1<count1)
      while((i2<count2) && (*(tab2+i2)<=*(tab1+i1)))
        *(temp+i++) = *(tab2+i2);


  // These two lines can be:
  // memcpy(tab2,temp+count1,i2*sizeof(int));

// MergeSort a table of integer of size count.
// Never tested.
void MergeSort(int *tab,int count)
  if (count==1) return;



(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)))
                               (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))
                (car primero)
                      (mergelist (cdr primero) segundo);;first main case
              ((> (cdar primero) (cdar segundo))
                (car segundo)
                      (mergelist primero (cdr segundo));;second main case

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))
        (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))


sort :: Ord a => [a] -> [a]

sort []         =  []
sort [x]        =  [x]
sort xs         =  merge (sort ys) (sort zs)
    (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


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 -> match halve t with t1, t2 -> 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 -> 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]


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)


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


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))

def merge(left, right)
  sorted = []
  until left.empty? or right.empty?
    if left.first <= right.first
      sorted << left.shift
      sorted << right.shift

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


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


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.

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.


External links


Wikipedia:Merge Sort