Skip to content

Instantly share code, notes, and snippets.

@griesmey
Created October 12, 2016 15:59
Show Gist options
  • Save griesmey/750a8a36efac803315f3b0c0db3ba72f to your computer and use it in GitHub Desktop.
Save griesmey/750a8a36efac803315f3b0c0db3ba72f to your computer and use it in GitHub Desktop.
Mergesort with Implicit Type ordering
import math.Ordering
def msort[T](xs: List[T])(implicit ord: Ordering[T]): List[T] = {
val n = xs.length / 2
if (n == 0) xs
else {
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 (fst, snd) = xs splitAt n
merge(msort(fst), msort(snd)
}
}
val l2 = List(6, 5, 4, 3, 2, 1)
val fruits = List("apple", "orange", "banana")
val l1 = msort(l2)
msort(fruits)
@griesmey
Copy link
Author

Mergesort in Scala

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment