在scala中对随机整数进行气泡排序。

问题描述 投票:0回答:1

我是Scala编程语言的新手,所以在这个Bubble排序中,我需要生成10个随机整数,而不是像下面的代码一样往右走,有什么建议吗? 对象BubbleSort { def bubbleSort()。

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 random bubble-sort
1个回答
2
投票

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

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

你可以找到更多信息 此处此处


3
投票

试试 这个:

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

2
投票

你可以用这种方式。

val solv1 = Random.shuffle( (1 to 100).toList).take(10)
val solv2 = Array.fill(10)(Random.nextInt)
© www.soinside.com 2019 - 2024. All rights reserved.