洞察探索如何通过一套代码实现跨平台小程序开发与高效管理,助力企业数字化转型
731
2023-08-04
Scala实现冒泡排序、归并排序和快速排序的示例代码
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: ListpVpMb[Int]): List[Int] = dataSet match {
case List() => List(data)
case head :: tail => if (data <= head) data :: dataSet else head :: compute(data,http:// 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, yhttp://List) 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 :pVpMb: 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))
}
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~