Created
October 17, 2012 16:42
-
-
Save jbochi/3906634 to your computer and use it in GitHub Desktop.
merge sort in scala
This file contains hidden or 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
def msort(xs: List[Int]): List[Int] = { | |
val n = xs.length / 2 | |
if (n == 0) xs | |
else { | |
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 (fst, snd) = xs splitAt n | |
merge(msort(fst), msort(snd)) | |
} | |
} //> msort: (xs: List[Int])List[Int] | |
val l = List(7, 2, 5, 1, 3, 1, 0, 9, -10) //> l : List[Int] = List(7, 2, 5, 1, 3, 1, 0, 9, -10) | |
msort(l) //> res0: List[Int] = List(-10, 0, 1, 1, 2, 3, 5, 7, 9) |
hltbra
commented
Nov 20, 2012
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment