scala冒泡排序
Posted 空山新雨后
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了scala冒泡排序相关的知识,希望对你有一定的参考价值。
scala冒泡排序:
object Maopao { def main(args: Array[String]) { val list = List(1, 23, 432, 10, 23, 42, 3, 23, 8, 23, 4) print(sort2(list)) println() val arr = Array(2, 5, 6, 7, 8, 10, 34, 656, 3) sort(arr) printArr(arr) } //基本的冒泡排序,类似java写法 def sort(arr: Array[Int]) = { for (i <- 0 until arr.length; j <- 0 until arr.length - 1; if (arr(j) > arr(j + 1))) { val temp = arr(j) arr(j) = arr(j + 1) arr(j + 1) = temp } } def printArr(arr: Array[Int]) = { for (i <- 0 until arr.length) print(arr(i) + ",") } def sort2(list: List[Int]): List[Int] = list match { case List() => List() case head :: tail => comput(head, sort2(tail)) } def comput(data: Int, dataSet: List[Int]): List[Int] = dataSet match { case List() => List(data) case head :: tail => if (data <= head) data :: dataSet else head :: comput(data, tail) } }
以上是关于scala冒泡排序的主要内容,如果未能解决你的问题,请参考以下文章