Skip to content

Instantly share code, notes, and snippets.

@bjarkevad
Created October 25, 2013 20:47
Show Gist options
  • Save bjarkevad/7161565 to your computer and use it in GitHub Desktop.
Save bjarkevad/7161565 to your computer and use it in GitHub Desktop.
mergesort in scala
object mergesort {
def msort[T](xs: List[T])(implicit ord: Ordering[T]): List[T] = {
val n = xs.length / 2
if (n == 0) xs
else {
def merge(xs: List[T], ys: List[T]): List[T] = (xs, ys) match {
case (Nil, ys) => ys
case (xs, Nil) => xs
case (x :: xs1, y :: ys1) =>
if (ord.lt(x, y)) x :: merge(xs1, ys)
else y :: merge(xs, ys1)
}
val (fst, snd) = xs splitAt n
merge(msort(fst), msort(snd))
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment