Scala实现冒泡排序、归并排序和快速排序的示例代码
1、冒泡排序
创新互联公司是一家以成都网站建设、网页设计、品牌设计、软件运维、网站推广、小程序App开发等移动开发为一体互联网公司。已累计为成都茶艺设计等众行业中小客户提供优质的互联网建站和软件开发服务。
def sort(list: List[Int]): List[Int] = list match { case List() => List() case head :: tail => compute(head, sort(tail)) } def compute(data: Int, dataSet: List[Int]): List[Int] = dataSet match { case List() => List(data) case head :: tail => if (data <= head) data :: dataSet else head :: compute(data, tail) } def main(args: Array[String]) { val list = List(3, 12, 43, 23, 7, 1, 2, 0) println(sort(list)) }
2、归并排序
def mergedSort[T](less: (T, T) => Boolean)(list: List[T]): List[T] = { def merged(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 :: merged(xTail, yList) else y :: merged(xList, yTail) } } } val n = list.length / 2 if (n == 0) list else { val (x, y) = list splitAt n merged(mergedSort(less)(x), mergedSort(less)(y)) } } def main(args: Array[String]) { val list = List(3, 12, 43, 23, 7, 1, 2, 0) println(mergedSort((x: Int, y: Int) => x < y)(list)) }
3、快速排序
def quickSort(list: List[Int]): List[Int] = { list match { case Nil => Nil case List() => List() case head :: tail => val (left, right) = tail.partition(_ < head) quickSort(left) ::: head :: quickSort(right) } } def main(args: Array[String]) { val list = List(3, 12, 43, 23, 7, 1, 2, 0) println(quickSort(list)) }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持创新互联。
文章标题:Scala实现冒泡排序、归并排序和快速排序的示例代码
路径分享:http://cdiso.cn/article/ppippd.html