Scala快速排序

来源:互联网 发布:哈希map java 编辑:程序博客网 时间:2024/06/07 00:15
import scala.util.Random/**  * Created by fhqplzj on 16-7-7 at 下午8:44.  */object QuickSort {  /**    * Scala快速排序    * @param less    * @param xs    * @tparam T    * @return    */  def qsort[T](less: (T, T) => Boolean)(xs: List[T]): List[T] = xs match {    case List() => xs    case x :: xs1 => {      val (left, right) = xs1.partition(less(_, x))      qsort(less)(left) ::: List(x) ::: qsort(less)(right)    }  }  def main(args: Array[String]) {    val random: Random = new Random(System.nanoTime())    val list: List[Int] = List.tabulate(10)(i => random.nextInt(100))    println("list = " + list)    val ascend: List[Int] = qsort[Int](_ < _)(list)    println("ascend = " + ascend)    val descend: List[Int] = qsort[Int](_ > _)(list)    println("descend = " + descend)  }}

0 0