当前位置: 代码迷 >> 综合 >> Scala 【List的高效排序】
  详细解决方案

Scala 【List的高效排序】

热度:44   发布时间:2024-02-12 20:18:05.0

package com.yl.Scala object sortList { def main(args: Array[String]){ def combineSort[T] (less: (T, T) => Boolean) (input: List[T]): List[T] = { /** * @param xList 要合并的有序列表 * @param yList 要合并的有序列表 * @return 合并后的列表 */ def combine(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 :: combine(xtail, yList) else y :: combine(xList, ytail) } val n = input.length / 2 if (n == 0) input else{ val(x, y) = input splitAt n //将要排序的列表平均分成两部分 combine(combineSort(less)(x), combineSort(less)(y)) //先对两个列表归并排序,然后再将有序表进行归并 } } //从小到大排序, x < y println(combineSort((x: Int, y: Int) => x < y) (List(3,4,2,6,45,5,56,7))) //从大到小排序, x > y println(combineSort((x: Int, y: Int) => x > y) (List(3,4,2,6,45,5,56,7))) } }

  相关解决方案