Created
August 6, 2013 14:13
-
-
Save deanh/6164844 to your computer and use it in GitHub Desktop.
Recursive Merge Sort.
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
// merge calls itself recursively | |
def merge(l1: List[Int], l2: List[Int]): List[Int] = { | |
// termination cases | |
if (l1.length == 0 && l2.length == 0) return Nil | |
if (l1.length == 0) return l2.head :: merge(Nil, l2.tail) | |
if (l2.length == 0) return l1.head :: merge(Nil, l1.tail) | |
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