Created
October 12, 2016 15:59
-
-
Save griesmey/750a8a36efac803315f3b0c0db3ba72f to your computer and use it in GitHub Desktop.
Mergesort with Implicit Type ordering
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
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) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Mergesort in Scala