Created
November 25, 2015 12:12
-
-
Save fancellu/5e00336840098c194551 to your computer and use it in GitHub Desktop.
MergeSort in Scala with recursive merge
This file contains 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
object MergeSort { | |
// recursive merge of 2 sorted lists | |
def merge(left: List[Int], right: List[Int]): List[Int] = | |
(left, right) match { | |
case(left, Nil) => left | |
case(Nil, right) => right | |
case(leftHead :: leftTail, rightHead :: rightTail) => | |
if (leftHead < rightHead) leftHead::merge(leftTail, right) | |
else rightHead :: merge(left, rightTail) | |
} | |
def mergeSort(list: List[Int]): List[Int] = { | |
val n = list.length / 2 | |
if (n == 0) list // i.e. if list is empty or single value, no sorting needed | |
else { | |
val (left, right) = list.splitAt(n) | |
merge(mergeSort(left), mergeSort(right)) | |
} | |
} | |
mergeSort(List(33,44,22,-10,99)) //> res0: List[Int] = List(-10, 22, 33, 44, 99) | |
mergeSort(List()) //> res1: List[Int] = List() | |
} |
Also the MergeSort function can be defined with pattern matching:
def mergeSort(list: List[Int]): List[Int] = list match {
case Nil => Nil
case xs::Nil => List(xs)
case _ =>
val (left, right) = list splitAt list.length/2
merge(mergeSort(left), mergeSort(right))
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
merge function can also be written as:
so that the 'left' and 'right' variables are not shadowed by the variables with same name having same lists respectively.