Skip to content

Instantly share code, notes, and snippets.

@alanktwong
Created December 12, 2012 22:31
Show Gist options
  • Select an option

  • Save alanktwong/4272265 to your computer and use it in GitHub Desktop.

Select an option

Save alanktwong/4272265 to your computer and use it in GitHub Desktop.
Merge sort in Scala using pattern matching
def mergeSort[T <: Ordered[T]](xs:List[T]): List[T] = {
def merge(xs:List[T], ys:List[T]): List[T] = {
(xs,ys) match {
case (Nil,_) => ys
case (_,Nil) => xs
case (x::xs1, y::ys1) => {
if (x < y) {
x::merge(xs1,ys)
} else {
y::merge(xs,ys1)
}
}
}
}
if (xs.isEmpty) {
xs
} else {
val n = xs.length / 2
val (ys,zs) = xs.splitAt(n)
merge(mergeSort(ys), mergeSort(zs))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment