Created
October 25, 2013 20:47
-
-
Save bjarkevad/7161565 to your computer and use it in GitHub Desktop.
mergesort in scala
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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