scala快速排序算法的实现

v7pvogib  于 2021-07-14  发布在  Java
关注(0)|答案(1)|浏览(325)

我需要帮助来填补一些空白,以便分区在调用分区(data,lower,upper)时工作。不过,我认为if语句应该是if(lower<upper-1),以避免浪费调用。另外,sortrange必须对范围[下限,上限]进行快速排序。我的问题是,在def sort[a](data:array[a])(…):unit={}的(…)中必须做些什么才能使它正常工作,如何实现swap以使它在具有一系列int的数组[a]上进行交换?

object Quicksort {
  def partition[A](data: Array[A], lower: Int, upper: Int)
                  (implicit comp: Ordering[A]): Int = {
    val pivot = data(upper-1)
    var mid = lower-1
    for (i <- lower until upper-1) {
      if (comp.lteq(data(i),pivot)) {
        mid += 1
        swap(data,mid,i)
      }
    }
    swap(data,mid+1,upper-1)
    mid+1
  }
  def sort[A](data: Array[A])(...): Unit = {
    def sortRange(data: Array[A], lower: Int, upper: Int):
    Unit = {
      if(lower < upper) {
        val pivotIndex = partition(data,lower,upper)
        sortRange(data,lower,pivotIndex)
        sortRange(data,pivotIndex+1,upper)
      }
    }
    sortRange(data,0,data.length)
  }
  def main(args: Array[String]) : Unit = {
    //Result of partition(data,lower,upper):
    //sortRange results in quick-sorting the range: [lower,upper)
  }
}
pkwftd7m

pkwftd7m1#

由于快速排序是一种就地排序算法(也就是说,它完全是关于副作用的),所以我不想传递要排序的集合,而是希望将该方法“附加”到所述集合。
我还想去掉那些讨厌的可变变量。

implicit class QSort[A:Ordering](as: Array[A]) {
  import Ordering.Implicits._
  private def swap(x: Int, y: Int): Unit = {
    val hold = as(x)
    as(x) = as(y)
    as(y) = hold
  }

  private def partition(lo: Int, hi: Int): Int =
    ((lo until hi).filter(as(_) < as(hi)) :+ hi)
      .zipWithIndex.foldLeft(0){
        case (_,(j,x)) => swap(j, lo+x); lo+x
      }

  private def quicksort(lo:Int, hi:Int): Unit =
    if (lo < hi) { 
      val p = partition(lo, hi)
      quicksort(lo, p-1)
      quicksort(p+1, hi)
    }

  def qsort(): Unit = quicksort(0, as.length - 1)
}

测试:

val cs = Array('g','a','t','b','z','h')
cs.qsort()  //: Unit
cs          //: Array[Char] = Array(a, b, g, h, t, z)

val ns = Array(9,8,7,6,5,4,3,2,1)
ns.qsort()  //: Unit
ns          //: Array[Int] = Array(1, 2, 3, 4, 5, 6, 7, 8, 9)

相关问题