Scala快速排序

Scala 快排

Scala


基本思想:经过一趟排序,把待排对象分成两个独立的部分,一部分的数据大(小)于另一部分,同理,对子对象进行如此处理,以达到所有数据都有序。

 

package student.scala

object Sort extends App {
  
   
  def quicksort[T <% Ordered[T]](xs:List[T]):List[T] = {
    if(xs.length <= 1 ) xs
    else {
           quicksort ( xs filter (xs(0) >) ) :::
                     (xs filter (xs(0) ==) ) :::
           quicksort ( xs filter (xs(0) <) )
    }
  }
  
  val rand = scala.util.Random
  
  val oriData = for(i <- 1 to 100) yield rand.nextInt(1000)
  
  oriData map (_ + " ") foreach  print 
  println
  quicksort(oriData.toList) map ( _ + " ") foreach print
  
  
  
}

 

下面是优化版的快排,可以接受更多的类型进行排序,而且返回值与传入值对应。

package student.scala

import scala.collection.SeqLike
import scala.collection.generic.CanBuildFrom

object Sort extends App {

  def quicksort[T <% Ordered[T]](xs: List[T]): List[T] = {

    if (xs.length <= 1) xs
    else {
      quicksort(xs filter (xs(0) >)) :::
        (xs filter (xs(0) ==)) :::
        quicksort(xs filter (xs(0) <))
    }
  }

  def sort[T, Coll](xs: Coll)(implicit
    ev0: Coll <:< SeqLike[T, Coll],
                              n:   Ordering[T],
                              cbf: CanBuildFrom[Coll, T, Coll]): Coll = {
    if (xs.length < 2) xs
    else {
      import n._
      val b = cbf()
      val pivot = xs.head
      b ++= sort(xs filter (pivot >))
      b ++= xs filter (pivot ==)
      b ++= sort(xs filter (pivot <))
      b.result
    }
  }

  val rand = scala.util.Random
  val list = for (i <- 1 to 10) yield rand.nextInt(100)

  val oriData = list

  oriData map (_ + " ") foreach print
  println
  sort(oriData) map (_ + " ") foreach print

}

 

 

posted on 2018-10-19 11:06  tneduts  阅读(407)  评论(1编辑  收藏

导航