object MergeSort { def msort[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) // or "xs splitAt n" merge(msort(less)(ys), msort(less)(zs)) } } def main(argv: Array[String]): Unit = { def compare(left: Int, right: Int): Boolean = { left <= right } val result = msort((x: Int, y: Int) => x < y)(List(9,8,7,6,5,4,3,2,1)) println(result) } }
摘自 《Programming in Scala》
时间: 2024-10-14 00:27:19