Scala 範例程式 - 函數式排序法 (Sort1)

原始程式:sort1.scala

/** Quick sort, functional style */
object sort1 {
  def sort(a: List[Int]): List[Int] = {
    if (a.length < 2)
      a
    else {
      val pivot = a(a.length / 2)
      sort(a.filter(_ < pivot)) :::
           a.filter(_ == pivot) :::
           sort(a.filter(_ > pivot))
    }
  }
  def main(args: Array[String]) {
    val xs = List(6, 2, 8, 5, 1)
    println(xs)
    println(sort(xs))
  }
}

執行結果:

D:\scala>scalac sort1.scala

D:\scala>scala sort1
List(6, 2, 8, 5, 1)
List(1, 2, 5, 6, 8)
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0 License