Skip to content

Instantly share code, notes, and snippets.

@sysarcher
Created December 29, 2016 22:14
Show Gist options
  • Save sysarcher/54584e19ca45e2000e5a304fe194fda1 to your computer and use it in GitHub Desktop.
Save sysarcher/54584e19ca45e2000e5a304fe194fda1 to your computer and use it in GitHub Desktop.
Scala and F# implementation of mergesort
let rec mergesort (xs: list<int>) =
let rec merge (xs: list<int>, ys: list<int>) =
match (xs, ys) with
| ([], ys) -> ys
| (xs, []) -> xs
| (x::xs1, y::ys1) ->
if(x < y) then x::merge(xs1, ys)
else y::merge(xs, ys1)
let n = xs.Length / 2
if (n = 0) then xs
else
let left, right = List.splitAt n xs
merge (mergesort left, mergesort right)
let r = System.Random()
mergesort (List.init 10 (fun index -> r.Next 500))
import scala.util.Random
def mergesort(xs: List[Int]): List[Int] = {
def merge(xs: List[Int], ys: List[Int]): List[Int] = {
(xs, ys) match {
case (Nil, ys) => ys
case (xs, Nil) => xs
case (x::xs1, y::ys1) =>
if (x < y) x::merge(xs1, ys)
else y::merge(xs, ys1)
}
}
val n = xs.length / 2
if(n==0) {
xs
} else {
val (left, right) = xs splitAt(n)
merge(mergesort(left), mergesort(right))
}
}
mergesort(List.fill(10)(Random.nextInt(500)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment