【问题标题】:Scala Quicksort algorithm implementationScala快速排序算法实现
【发布时间】:2023-03-30 09:15:01
【问题描述】:

我需要帮助填写一些空白,以便分区在调用分区(数据、下层、上层)时起作用。虽然,我认为 if 语句应该是 if (lower

 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)
  }
}

【问题讨论】:

  • 你试过什么?你了解隐式和类型参数/泛型的概念吗?
  • @mchaJIS 我相信implicits对数据强加了一个排序(整数小于这个意义上的整数)并且类型参数/泛型(例如类型A)可以在实例化时间

标签: scala array-algorithms


【解决方案1】:

由于 Quicksort 是一种就地排序算法(即,它都是关于副作用的),而不是传递要排序的集合,我想将方法​​“附加”到所述集合。

我还想删除所有那些讨厌的可变变量。

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)

【讨论】:

  • 对于您的角色示例,当我执行 val cs = Array('g','a','t','b','z','h') println(cs .mkString("Array(", ", ", ")")) 它只输出 Array(g, a, t, z) 而不是 Array(g, a, t, b, z, h)?
  • for me scala> val cs = Array('g','a','t','b','z','h') cs: Array[Char] = Array( g, a, t, b, z, h) scala> println(cs.mkString("Array(", ", ", ")")) Array(g, a, t, z)
  • 我看到对其他人来说它按预期工作,所以可能是我正在使用的版本,或者只是我的一些小故障。我想这是 2.13.0 中的一些奇怪的错误
猜你喜欢
  • 1970-01-01
  • 2023-01-31
  • 2018-09-20
  • 2022-06-21
  • 1970-01-01
  • 2018-03-17
  • 2014-04-25
  • 2010-11-28
  • 2019-05-01
相关资源
最近更新 更多