Skip to content

Instantly share code, notes, and snippets.

@ZilvinasKucinskas
Last active December 25, 2015 17:49
Show Gist options
  • Save ZilvinasKucinskas/7015751 to your computer and use it in GitHub Desktop.
Save ZilvinasKucinskas/7015751 to your computer and use it in GitHub Desktop.
Merge sort function in Scala; Average complexity: O(n * log(n)); Worst complexity: O(n * log(n));
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