Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@fayvor
Forked from deanh/gist:6164844
Last active December 20, 2015 16:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save fayvor/6165505 to your computer and use it in GitHub Desktop.
Save fayvor/6165505 to your computer and use it in GitHub Desktop.
// merge calls itself recursively
def merge(l1: List[Int], l2: List[Int]): List[Int] = {
// termination cases
(l1, l2) match {
case (Nil, Nil) => Nil
case (x, Nil) => x
case (Nil, y) => y
case (_, _) => l1.head.compare(l2.head) match {
case -1 => l1.head :: merge(l1.tail, l2)
case _ => l2.head :: merge(l2.tail, l1)
}
}
}
// mergeSort calls itself AND merge recursively
def mergeSort(list: List[Int]): List[Int] = {
// termination case
if (list.length < 2)
list
else {
val part = list.splitAt(list.length / 2)
merge(mergeSort(part._1), mergeSort(part._2))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment