scala中随机整数的冒泡排序

Bubble sort of random integers in scala

我是 Scala 编程语言的新手,所以在这个冒泡排序中我需要生成 10 个随机整数,而不是像下面的代码那样正确 有什么建议吗?

object BubbleSort {

  def bubbleSort(array: Array[Int]) = {
    def bubbleSortRecursive(array: Array[Int], current: Int, to: Int): Array[Int] = {
        println(array.mkString(",") + "    current -> " + current + ", to -> " + to)
        to match {
          case 0 => array
          case _ if(to == current) => bubbleSortRecursive(array, 0, to - 1)
          case _ =>
            if (array(current) > array(current + 1)) {
            var temp = array(current + 1)
            array(current + 1) = array(current)
            array(current) = temp
          }
          bubbleSortRecursive(array, current + 1, to)
        }
    }
    bubbleSortRecursive(array, 0, array.size - 1)
  }

  def main(args: Array[String]) {
    val sortedArray = bubbleSort(Array(10,9,11,5,2))
    println("Sorted Array -> " + sortedArray.mkString(","))
  }
}

可以使用scala.util.Random生成。 nextInt 方法采用 maxValue 参数,因此在代码示例中,您将生成从 0 到 100 的 10 个 int 值的列表。

val r = scala.util.Random
for (i <- 1 to 10) yield r.nextInt(100)

您可以找到更多信息here or here

尝试 this:

import scala.util.Random
val sortedArray = (1 to 10).map(_ => Random.nextInt).toArray

你可以这样使用它。

val solv1 = Random.shuffle( (1 to 100).toList).take(10)
val solv2 = Array.fill(10)(Random.nextInt)