scala入门初级代码训练-32List的排序问题

原创文章,转载请注明出处!

原文地址: http://www.ptbird.cn/2016/07/19/scala-chuji-demo-32/

There I am,in the world more exciting!

by postbird

www.ptbird.cn



package com.ptbird.scala

/**
* Created by postbird on 2016/5/26.
*
* List的排序与倒排序
*/
object ListTest3 {
def main(args: Array[String]): Unit = {

//List使用原生的排序方法 效率很低

def mergedSort[T](less: (T, T) => Boolean)(input: List[T]): List[T] = {

def merge(xList: List[T], yList: List[T]): List[T] = (xList, yList) match {
case (Nil, _) => yList
case (_, Nil) => xList
case (x :: xtail, y :: ytail) => if (less(x, y)) x :: merge(xtail, yList)
else y :: merge(xList, ytail)
}
val n = input.length / 2
if (n == 0) input
else {
val (x, y) = input splitAt n
merge(mergedSort(less)(x), mergedSort(less)(y))
//对切分的两部分进行归并排序,在对排好顺序的有序表进行归并
}
}

println(mergedSort((x: Int, y: Int) => x x > y) _
println(reversed_mergedsort(List(3, 7, 9, 5)))
// List(3, 5, 7, 9)
// List(9, 7, 5, 3)

}

}

欢迎评论。
lingkb » scala入门初级代码训练-32List的排序问题

发表评论