Skip to content

Instantly share code, notes, and snippets.

@samidarko
Created September 20, 2016 10:10
Show Gist options
  • Save samidarko/f41c34cc98fda988c838cc519d0ecbd4 to your computer and use it in GitHub Desktop.
Save samidarko/f41c34cc98fda988c838cc519d0ecbd4 to your computer and use it in GitHub Desktop.
Merge Sort in Scala
/**
* Created by samidarko on 9/20/16.
*/
import util.Random
object MergeSort extends App {
def merge(left: List[Int], right: List[Int]) : List[Int] = {
if (left.isEmpty) right
else if (right.isEmpty) left
else {
if (left.head < right.head) left.head :: merge(left.tail, right)
else right.head :: merge(left, right.tail)
}
}
def mergeSort(l: List[Int]) : List[Int] = {
if (l.length == 1) l
else {
val (left, right) = l.splitAt(l.length/2)
merge(mergeSort(left), mergeSort(right))
}
}
val l = List(5,3,7,5,8,2,9,1)
assert(mergeSort(l) == l.sorted)
val randomList = Seq.fill(6)(Random.nextInt(100)).toList
assert(mergeSort(randomList) == randomList.sorted)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment