Skip to content

Instantly share code, notes, and snippets.

@mzimecki
Created October 16, 2013 09:20
Show Gist options
  • Save mzimecki/7005003 to your computer and use it in GitHub Desktop.
Save mzimecki/7005003 to your computer and use it in GitHub Desktop.
[Scala] Merge sort with implicit parameter used for comparing elements in a list. Making prameter implicit will cause compiler will discover type of elements in a list to be sorted.
object MergeSort {
def msort[T](xs: List[T])(implicit ord: Ordering[T]): List[T] = {
def merge(xs: List[T], ys: List[T]): List[T] = (xs, ys) match {
case (Nil, ys) => ys
case (xs, Nil) => xs
case (x :: xs1, y :: ys1) =>
if (ord.lt(x, y)) x :: merge(xs1, ys) else y :: merge(xs, ys1)
}
val n = xs.length / 2
if (n == 0) xs
else {
val (fst, snd) = xs splitAt n
merge(msort(fst), msort(snd))
}
}
def main(args: Array[String]) = {
val list = MergeSort.msort(List(4, 5, 7, 33, 6))
for (l <- list)
print(l + " ")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment