Skip to content

Instantly share code, notes, and snippets.

@dschobel
Created November 5, 2012 04:20
Show Gist options
  • Save dschobel/4015295 to your computer and use it in GitHub Desktop.
Save dschobel/4015295 to your computer and use it in GitHub Desktop.
mergesort in scala
val r = new scala.util.Random()
val data = List.fill(10)(r.nextInt(100))
def msort(data: List[Int]): List[Int] = {
def merge(xs: List[Int], ys: List[Int]): List[Int] = (xs, ys) match {
case (List(), _) => ys
case (_, List()) => xs
case (x :: xs1, y :: ys1) => if (x < y) x :: merge(xs1, ys) else y :: merge(xs, ys1)
}
val n = data.length / 2
if (n == 0)
data
else {
val (first, second) = data.splitAt(n)
merge(msort(first), msort(second))
}
}
msort(data)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment