Skip to content

Instantly share code, notes, and snippets.

@allieus
Created April 21, 2013 15:24
Show Gist options
  • Save allieus/5429979 to your computer and use it in GitHub Desktop.
Save allieus/5429979 to your computer and use it in GitHub Desktop.
def merge_sort[T](less: (T, T) => Boolean)(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 (less(x, y))
x :: merge(xs1, ys)
else
y :: merge(xs, ys1)
}
val n = xs.length / 2
if (n == 0)
xs
else {
val (ys, zs) = xs splitAt n
merge(merge_sort(less)(ys), merge_sort(less)(zs))
}
}
println(merge_sort((x: Int, y: Int) => x < y)(List(5, 7, 1, 3)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment