选择在Scala中排序

时间:2016-05-03 17:28:26

标签: scala sorting

我是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
    }
}

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

选择按功能样式排序:

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