为什么这个Scala bubbleSorting不起作用?

时间:2017-02-19 04:18:51

标签: scala bubble-sort

这是scala的冒泡代码实现,但它无法正常工作。

implicit class ArrayWrappedSwap[A](array: Array[A]){
    def swap(current:Int,target:Int): Unit ={
      val tmp = array(target)
      array(target) = array(current)
      array(current) = tmp
    }
 }
 def bubbleSort[A](arr:Array[A])(implicit ordering: Ordering[A]):Array[A]={
    var continueSort = true

    arr.indices.foreach(time⇒ {

      if (!continueSort) {
        return arr

      } else {
        continueSort = false

        (0 until (arr.length - time)).foreach { index ⇒

          if (ordering.compare(arr(index), arr(arr.length - 1 - time)) > 0) {
            arr.swap(index, arr.length - 1 - time)
            continueSort = true
          }

        }
      }
    })
    arr
 }
println(bubbleSort(Array(1,3,1,2,3)).mkString(","))

输出1,3,1,2,3

1 个答案:

答案 0 :(得分:0)

这是一个真正做出bubbleort的固定版本。我不知道你希望其他版本如何工作,所以这只是明显的“比较每对相邻的项目”

  implicit class ArrayWrappedSwap[A](array: Array[A]) {
    def swap(current: Int, target: Int): Unit = {
      val tmp = array(target)
      array(target) = array(current)
      array(current) = tmp
    }
  }
  def bubbleSort[A](arr: Array[A])(implicit ordering: Ordering[A]): Array[A] = {
    var continueSort = true

    arr.indices.foreach(time => {

      if (!continueSort) {
        return arr

      } else {
        continueSort = false

        (time  until arr.length-1).foreach { index =>

          if (ordering.compare(arr(index), arr(index + 1)) > 0) {
            arr.swap(index, index+1)
            continueSort = true
          }

        }
      }
    })
    arr
  }                                               //> bubbleSort: [A](arr: Array[A])(implicit ordering: Ordering[A])Array[A]
  println(bubbleSort(Array(1, 3, 1, 2, 3)).mkString(","))