Skip to content

Instantly share code, notes, and snippets.

@ArionHardison
Created October 9, 2014 21:24
Show Gist options
  • Save ArionHardison/ac68079343f45918f8f6 to your computer and use it in GitHub Desktop.
Save ArionHardison/ac68079343f45918f8f6 to your computer and use it in GitHub Desktop.
// http://en.wikipedia.org/wiki/Merge_sort
let rec mergeSort (arr : 'a []) =
let split (arr : _ array) =
let n = arr.Length
arr.[0..n/2-1], arr.[n/2..n-1]
let rec merge (l : 'a array) (r : 'a array) =
let n = l.Length + r.Length
let res = Array.zeroCreate<'a> n
let mutable i, j = 0, 0
for k = 0 to n-1 do
if i >= l.Length then res.[k] <- r.[j]; j <- j + 1
elif j >= r.Length then res.[k] <- l.[i]; i <- i + 1
elif l.[i] < r.[j] then res.[k] <- l.[i]; i <- i + 1
else res.[k] <- r.[j]; j <- j + 1
res
match arr with
| [||] | [| _ |] -> arr
| _ -> let (x, y) = split arr
merge (mergeSort x) (mergeSort y)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment