Merge sort

From CodeCodex

Merge sort examples in 24 languages.

Related content:


Contents

Implementations

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

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;

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


C++

Here is a recursive implementation of the merge sort using STL vectors (This is a naive implementation):

//! \brief Performs a recursive merge sort on the given vector
//! \param vec The vector to be sorted using the merge sort
//! \return The sorted resultant vector after merge sort is
//! complete.
vector<int> merge_sort(vector<int>& vec)
{
    // Termination condition: List is completely sorted if it
    // only contains a single element.
    if(vec.size() == 1)
    {
        return vec;
    }

    // Determine the location of the middle element in the vector
    std::vector<int>::iterator middle = vec.begin() + (vec.size() / 2);

    vector<int> left(vec.begin(), middle);
    vector<int> right(middle, vec.end());

    // Perform a merge sort on the two smaller vectors
    left = merge_sort(left);
    right = merge_sort(right);

    return merge(left, right);
}

And here is the implementation of the merge function:

//! \brief Merges two sorted vectors into one sorted vector
//! \param left A sorted vector of integers
//! \param right A sorted vector of integers
//! \return A sorted vector that is the result of merging two sorted
//! vectors.
vector<int> merge(const vector<int>& left, const vector<int>& right)
{
    // Fill the resultant vector with sorted results from both vectors
    vector<int> result;
    unsigned left_it = 0, right_it = 0;

    while(left_it < left.size() && right_it < right.size())
    {
        // If the left value is smaller than the right it goes next
        // into the resultant vector
        if(left[left_it] < right[right_it])
        {
            result.push_back(left[left_it]);
            left_it++;
        }
        else
        {
            result.push_back(right[right_it]);
            right_it++;
        }
    }

    // Push the remaining data from both vectors onto the resultant
    while(left_it < left.size())
    {
        result.push_back(left[left_it]);
        left_it++;
    }

    while(right_it < right.size())
    {
        result.push_back(right[right_it]);
        right_it++;
    }

    return result;
}

Here's another recursive implementation of the mergesort using arrays of variable length

#include <iostream>
using namespace std;


void merge(int a[], const int low, const int mid, const int high)
{
	// Variables declaration. 
	int * b = new int[high+1-low];
	int h,i,j,k;
	h=low;
	i=0;
	j=mid+1;
	// Merges the two array's into b[] until the first one is finish
	while((h<=mid)&&(j<=high))
	{
		if(a[h]<=a[j])
		{
			b[i]=a[h];
			h++;
		}
		else
		{
			b[i]=a[j];
			j++;
		}
		i++;
	}
	// Completes the array filling in it the missing values
	if(h>mid)
	{
		for(k=j;k<=high;k++)
		{
			b[i]=a[k];
			i++;
		}
	}
	else
	{
		for(k=h;k<=mid;k++)
		{
			b[i]=a[k];
			i++;
		}
	}
	// Prints into the original array
	for(k=0;k<=high-low;k++) 
	{
		a[k+low]=b[k];
	}
	delete[] b;
}

void merge_sort(int a[], const int low, const int high)		// Recursive sort ...
{
	int mid;
	if(low<high)
	{
		mid=(low+high)/2;
		merge_sort(a, low,mid);
		merge_sort(a, mid+1,high);
		merge(a, low,mid,high);
	}
}

int _tmain(int argc, _TCHAR* argv[])
{
	int arraySize;
	// a[] is the array to be sorted. ArraySize is the size of a[] ...
	merge_sort(a, 0, (arraySize-1) );        // would be more natural to use merge_sort(a, 0, arraySize ), so please try ;-)

	// some work 
	return 0;
}

C#

        public IList MergeSort(IList list)
        {
            if (list.Count <= 1)
                return list;

            int mid = list.Count / 2;

            IList left = new ArrayList();
            IList right = new ArrayList();

            for (int i = 0; i < mid; i++)
                left.Add(list[i]);

            for (int i = mid; i < list.Count; i++)
                right.Add(list[i]);

            return Merge(MergeSort(left), MergeSort(right));
        }

        public IList Merge(IList left, IList right) 
        {
            IList rv = new ArrayList();
            
            while (left.Count > 0 && right.Count > 0)
                if (((IComparable)left[0]).CompareTo(right[0]) > 0)
                {
                    rv.Add(right[0]);
                    right.RemoveAt(0);
                }
                else
                {
                    rv.Add(left[0]);
                    left.RemoveAt(0);
                }

            for (int i = 0; i < left.Count; i++)
                rv.Add(left[i]);

            for (int i = 0; i < right.Count; i++)
                rv.Add(right[i]);

            return rv;
        }

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

Eiffel


class
	APPLICATION

create
	make

feature -- Initialization

	make is
           --
             do

	       end

feature -- Algorithm

	mergesort(a:ARRAY[INTEGER]; l,r:INTEGER) is
			-- Recursive mergesort

		local
			m: INTEGER
		do
			if l<r then
				m := (l+r)//2
				mergesort(a,l, m)
				mergesort(a,m+1,r)
				merge(a,l,m,r)

			end
		end

feature -- Utility feature

	merge(a:ARRAY[INTEGER]; l,m,r: INTEGER) is
			-- The merge feature of all mergesort variants
		local
			b: ARRAY[INTEGER]
			h,i,j,k: INTEGER

		do
			i := l
			j := m+1
			k := l
			create b.make (l, r)

			from

			until
				i > m or j > r
			loop
				-- begins the merge and copies it into an array "b"
				if a.item (i) <= a.item (j) then
					b.item (k) := a.item (i)
					i := i +1

				elseif a.item (i) > a.item (j) then
					b.item (k) := a.item (j)
					j := j+1
				end
				k := k+1
			end

				-- Finishes the copy of the uncopied part of the array
			if i > m then
				from
					h := j
				until
					h > r
				loop
					b.item (k+h-j) := a.item (h)
					h := h+1
				end

			elseif j > m then

				from
					h := i
				until
					h > m
				loop
					b.item (k+h-i) := a.item (h)
					h := h+1
				end
			end

			-- "begins the copy to the real array"

			from
				h := l
			until
				h > r
			loop
				a.item (h) := b.item (h)
				h := h+1
			end

		end

feature -- Attributes

	array: ARRAY[INTEGER]

Erlang

merge_sort(List) when length(List) =< 1 -> List;
merge_sort(List) ->
    {Left, Right} = lists:split(length(List) div 2, List),
    lists:merge(merge_sort(Left), merge_sort(Right)).

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

Groovy


def mergeSort(list){
 if( list.size() <= 1) return list
  center = list.size() / 2
  left  = list[0..center]
  right = list[center..list.size()]
  merge(mergeSort(left), mergeSort(right))
}

def merge(left, right){
  sorted = []
  while(left.size() > 0 || right.size() > 0)
    if(left.get(0) <= right.get(0)){
      sorted << left
    }else{
      sorted << right
    }
  sorted = sorted + left + right
}

Haskell

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

sort []    =  []
sort [x]  =  [x]
sort xs   =  merge (sort left) (sort right)
  where
    (left, right) = splitAt (length xs `div` 2) xs
    merge [] xs = xs
    merge xs [] = xs
    merge (x:xs) (y:ys)
      | x <= y      = x : merge xs (y:ys)
      | otherwise = y : merge (x:xs) ys

Java

 public int[] mergeSort(int array[])  {
 	if(array.length > 1)  	{
 		int elementsInA1 = array.length/2;
 		int elementsInA2 = array.length - elementsInA1;
 		int arr1[] = new int[elementsInA1];
 		int arr2[] = new int[elementsInA2];
 		
 		for(int i = 0; i < elementsInA1; i++)
 			arr1[i] = array[i];

 		for(int i = elementsInA1; i < elementsInA1 + elementsInA2; i++)
 			arr2[i - elementsInA1] = array[i];

 		arr1 = mergeSort(arr1);
 		arr2 = mergeSort(arr2);
 		
 		int i = 0, j = 0, k = 0;

 		while(arr1.length != j && arr2.length != k) {
 			if(arr1[j] <= arr2[k]) {
 				array[i] = arr1[j];
 				i++;
 				j++;
 			} else {
 				array[i] = arr2[k];
 				i++;
 				k++;
 			}
 		}

 		while(arr1.length != j) {
 			array[i] = arr1[j];
 			i++;
 			j++;
 		}
 		while(arr2.length != k) {
 			array[i] = arr2[k];
 			i++;
 			k++;
 		}
 	}
 	return array;
 }

JavaScript

function merge_sort(arr) {
    var l = arr.length, m = Math.floor(l/2);
    if (l <= 1) return arr;
    return merge(merge_sort(arr.slice(0, m)), merge_sort(arr.slice(m)));
}

function merge(left,right) {
    var result = [];
    var ll = left.length, rl = right.length;
    while (ll > 0 && rl > 0) {
        if (left[0] <= right[0]) {
            result.push(left.shift());
            ll--;
        } else {
            result.push(right.shift());
            rl--;
        }
    }
    if (ll > 0) {
        result.push.apply(result, left);
    } else if (rl > 0) {
        result.push.apply(result, right);
    }
    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

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]

Opal

Signature:

SIGNATURE Merge[alpha,<]

IMPORT Array[alpha] ONLY array
       Seq   ONLY seq 
       Nat ONLY nat

SORT alpha 
FUN < : alpha ** alpha -> bool

FUN mergeSort:  seq[alpha] -> seq[alpha]

Implementation

IMPLEMENTATION Merge[alpha,<]


IMPORT Array[alpha] COMPLETELY
       Seq          COMPLETELY
       Nat          COMPLETELY
       Bool         COMPLETELY

FUN merge: seq[alpha] ** seq[alpha] -> seq[alpha]
DEF merge((<>),B) == B
DEF merge(A,(<>)) == A
DEF merge(A AS (a::as),B AS (b::bs) ) == IF a < b THEN a::merge(as,B) ELSE b::merge(A,bs) FI

DEF mergeSort(<>) == <>
DEF mergeSort(A AS (a::(<>))) == A
DEF mergeSort(lst) == LET 
                        half == #(lst)/2
                        (a,b) == split(half,lst)
                      IN 
                      merge(mergeSort(a),mergeSort(b))

Perl

FYI as of perl's built-in sort is merge sort by default.

#!/usr/bin/perl
use strict;
use warnings;

sub mergesort;    # to suppress prototype warnings

sub mergesort(&@) {
    my $comp = shift;
    return @_ if @_ <= 1;
    my @tail = splice @_, @_ >> 1;
    merge( $comp, [ mergesort $comp, @_ ], [ mergesort $comp, @tail ] );
}

sub merge {
    my ( $comp, $head, $tail ) = @_;
    my @ret;
    while ( @$head && @$tail ) {
        push @ret,
          (
            $comp->( $head->[0], $tail->[0] ) < 0
            ? shift @$head
            : shift @$tail
          );
    }
    push @ret, @$head, @$tail;
    @ret;
}

my @rnd = map { int( rand 100 ) } 1 .. 20;
print join( ",", @rnd ), "\n";
print join( ",", mergesort { $_[0] <=> $_[1] } @rnd ), "\n";
print join( ",", sort { $a <=> $b } @rnd ), "\n";

PHP

1:

function merge_sort(&$arrayToSort)
{
    if (sizeof($arrayToSort) <= 1)
        return $arrayToSort;

    // split our input array into two halves
    // left...
    $leftFrag = array_slice($arrayToSort, 0, (int)(count($arrayToSort)/2));
    // right...
    $rightFrag = array_slice($arrayToSort, (int)(count($arrayToSort)/2));

    // RECURSION
    // split the two halves into their respective halves...
    $leftFrag = merge_sort($leftFrag);
    $rightFrag = merge_sort($rightFrag);

    $returnArray = merge($leftFrag, $rightFrag);

    return $returnArray;
}


function merge(&$lF, &$rF)
{
    $result = array();

    // while both arrays have something in them
    while (count($lF)>0 && count($rF)>0) {
        if ($lF[0] <= $rF[0]) {
            array_push($result, array_shift($lF));
        }
        else {
            array_push($result, array_shift($rF));
        }
    }

    // did not see this in the pseudo code,
    // but it became necessary as one of the arrays
    // can become empty before the other
    array_splice($result, count($result), 0, $lF);
    array_splice($result, count($result), 0, $rF);

    return $result;
}

2:


function merge_sort(&$a) {
	if (count($a) == 1) return;
	$b = array_splice($a, count($a) / 2);
	merge_sort($a);
	merge_sort($b);
	$o = array();
	while (!empty($a) || !empty($b)) {
		if (empty($a) || empty($b)) $o[] = empty($a) ? array_shift($b) : array_shift($a);
		else $o[] = $a[0] > $b[0] ? array_shift($b) : array_shift($a);
	}
	$a = $o;
}

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

Python

def mergesort(arr):
    if len(arr) == 1:
        return arr
    
    m = len(arr) / 2
    l = mergesort(arr[:m])
    r = mergesort(arr[m:])

    if not len(l) or not len(r):
        return l or r
        
    result = []
    i = j = 0
    while (len(result) < len(r)+len(l)):        
        if l[i] < r[j]:
            result.append(l[i])
            i += 1
        else:
            result.append(r[j])
            j += 1            
        if i == len(l) or j == len(r):            
            result.extend(l[i:] or r[j:])
            break
        
    return result

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

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

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]

Tcl

proc mergesort list {
 set len [llength $list]
 if {$len <= 1} {return $list}
 set middle [expr {$len / 2}]
 set left [lrange $list 0 [expr {$middle - 1}]]
 set right [lrange $list $middle end]
 return [merge [mergesort $left] [mergesort $right]]
}
 
proc merge {left right} {
 set res {}
 while {[set lleft [llength $left]] > 0 && [set lright [llength $right]] > 0} {
      if {[lindex $left 0] <= [lindex $right 0]} {
        set left [lassign $left value]
      } else {
        set right [lassign $right value]
      }
      lappend res $value
 }
 if {$lleft > 0} {lappend res {*}$left}
 if {$lright > 0} {set res [concat $res $right]}
 return $res
}

Standard ML

fun mergesort [] = []
|   mergesort [x] = [x]
|   mergesort lst = 
    let fun merge ([],ys) = ys (*merges two sorted lists to form a sorted list *)
        |   merge (xs,[]) = xs
        |   merge (x::xs,y::ys) = 
              if x<y then
                x::merge (xs,y::ys)
              else
                y::merge (x::xs,ys)
        ; 
        val half = length(lst) div 2;
     in
        merge (mergesort (List.take (lst, half)),mergesort (List.drop (lst, half)))
     end
;

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.

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