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) } }
时间: 2024-11-05 12:19:24