您好,登錄后才能下訂單哦!
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)) }
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。