Skip to content

Instantly share code, notes, and snippets.

@RyanSusana
Created June 2, 2020 07:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RyanSusana/8afbef3050b8e0348cea2afee73fe419 to your computer and use it in GitHub Desktop.
Save RyanSusana/8afbef3050b8e0348cea2afee73fe419 to your computer and use it in GitHub Desktop.
def mergeSort(xs: List[Int]): List[Int] = {
val n = xs.length / 2
if (n == 0) xs
else {
val (firstHalf, secondHalf) = xs splitAt n
merge(mergeSort(firstHalf), mergeSort(secondHalf))
}
}
def merge(xs: List[Int], ys: List[Int]): List[Int] =
(xs, ys) match {
case (Nil, ys) => ys
case (xs, Nil) => xs
case (x :: xTail, y :: yTail) =>
if (x < y) x :: merge(xTail, ys) else y :: merge(yTail, xs)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment