Scala学习笔记24【List的高效排序】
2015-10-16 13:57
351 查看
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))) } }
运行结果:
List(2, 3, 4, 5, 6, 7, 45, 56) List(56, 45, 7, 6, 5, 4, 3, 2)
相关文章推荐
- android 中Bn 和Bp的区别
- oc 数组Array
- ios创建视图的一些方法封装
- maven常用插件: 打包源码 / 跳过测试 / 单独打包依赖项
- 深拷贝和浅拷贝(mutableCopy和Copy)详解
- JAVA导出EXCEL并下载
- Android Studio中添加对HttpClient的支持包
- node.js与websocket入门
- [No000022]他们说:得诺贝尔奖到底有多难?
- css hack
- ECSHOP的订单状态在数据库中的表现(order_status, shipping_status, pay_status)
- CentOS 7 巨大变动之 systemd 取代 SysV的Init
- 把想法变成现实-兄弟连IT教育
- Android应用性能测试
- 王健林=马云+2个刘强东—《2015胡润百富榜》
- Spring Security(15)——权限鉴定结构
- soapui测试JDBC数据库
- [No000021]跟维多利亚学英语
- [LeetCode]题解(python):026-Remove Duplicates from Sorted Array
- BZOJ 3751 [NOIP2014]解方程 百年老坑填坑计划QAQ--Hash