Scala实现冒泡排序、归并排序和快速排序的示例代码

时间:2021-05-20

1、冒泡排序

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)) }

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章