Sorting algorithms/Merge sort

Revision as of 19:22, 5 February 2008 by rosettacode>Mwn3d (Created page trying to encourage examples.)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

The merge sort is an order n*log(n) (technically n*lg(n)--lg is log base 2) sort. The basic idea is to split the collection into smaller groups by halving it until the groups only have one element (which is an entirely sorted group). Then merge the groups back together so that their elements are in order.

Task
Sorting algorithms/Merge sort
You are encouraged to solve this task according to the task description, using any language you may know.

Write a function to sort an array of integers using the merge sort. The merge sort algorithm comes in two parts: a sort function and a merge function. The functions in pseudocode look like this:

function mergesort(m)
   var list left, right, result
   if length(m) ≤ 1
       return m
   else
       var 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
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 rest(left) to result
   if length(right) > 0 
       append rest(right) to result
   return result