【问题标题】:Selection Sort in ScalaScala中的选择排序
【发布时间】:2016-08-28 21:08:39
【问题描述】:

我是 Scala 新手,正在尝试选择排序算法。我设法进行了最小排序,但是当我尝试进行最大排序时,我得到了一个排序数组,但按降序排列。我的代码是:

def maxSort(a:Array[Double]):Unit = {
    for(i <- 0 until a.length-1){
            var min = i
                    for(j <- i + 1 until a.length){
                            if (a(j) < a(min)) min = j
            }
    val tmp = a(i)
    a(i) = a(min)
    a(min) = tmp
    }
}

我知道我必须将结果附加到数组的末尾,但我该怎么做呢?

【问题讨论】:

    标签: scala sorting


    【解决方案1】:

    选择功能风格的排序:

      def selectionSort(source: List[Int]) = {
        def select(source: List[Int], result: List[Int]) : List[Int] = source match {
          case h :: t => sort(t, Nil, result, h) 
          case Nil => result
        }
        @tailrec
        def sort(source: List[Int], r1: List[Int], r2: List[Int], m: Int) : List[Int] = source match {
          case h :: t => if( h > m) sort(t, h :: r1, r2, m) else  sort(t, m :: r1, r2, h)
          case Nil =>  select(r1, r2 :+ m)
        }
        select(source, Nil)
      }
    

    【讨论】:

      【解决方案2】:

      此代码将使用最大值按升序对数组进行排序:

      def maxSort(a:Array[Double]):Unit = {
        for (i <- (0 until a.length).reverse) {
          var max = i
          for (j <- (0 until i).reverse) {
            if (a(j) > a(max)) max = j
          }
          val tmp = a(i)
          a(i) = a(max)
          a(max) = tmp
        }
      }
      

      这里的主要问题是以相反的顺序遍历数组,这里提供了更多的解决方案: Scala downwards or decreasing for loop?

      请注意,Scala 因其函数式特性而备受赞誉,函数式方法可能更有趣且“符合语言风格”。以下是选择排序的一些示例:

      Selection sort in functional Scala

      【讨论】:

      • 感谢您的回答和参考。
      猜你喜欢
      • 2010-12-12
      • 2013-04-25
      • 2020-03-12
      • 1970-01-01
      • 2014-08-26
      • 2013-01-19
      • 2018-04-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多