Scala 过程陷入无限循环(我认为)

发布于 2024-12-04 01:25:32 字数 636 浏览 0 评论 0原文

以下代码是数组排序算法的手动版本,获取任何整数数组,并更改该数组,使其处于非递减顺序。由于某种原因,当我在数组上调用这个过程时,我的 scala 控制台就坐在那里(似乎在计算东西),我不知道为什么。

def main(a: Array[Int]) {
    var l = a.length
    var switchesLeft = true

    while( switchesLeft == true) {

      var z = 0
      var i = 0;

      while( i < l ) {
        var x = i + 1

        if( x == l ) x = 0

        if( a(i) > a(x) ) {
          // Switch the elements
          var t = a(x)
          a(x) = a(i)
          a(i) = t

          z += 1;
        }

        i += 1
      }

      if( z == 0) {
        // No switches were done
        switchesLeft = false
      }

    }
}

The following code is a manual version of an array sorting algorithm, taking any array of integers, and changing that array so that it is in non-decreasing order. For some reason, my scala console just sits there (seemingly computing things) when I call this procedure on an array, and I don't know why.

def main(a: Array[Int]) {
    var l = a.length
    var switchesLeft = true

    while( switchesLeft == true) {

      var z = 0
      var i = 0;

      while( i < l ) {
        var x = i + 1

        if( x == l ) x = 0

        if( a(i) > a(x) ) {
          // Switch the elements
          var t = a(x)
          a(x) = a(i)
          a(i) = t

          z += 1;
        }

        i += 1
      }

      if( z == 0) {
        // No switches were done
        switchesLeft = false
      }

    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

烟火散人牵绊 2024-12-11 01:25:32

循环的原因是if( x == l ) x = 0。省略它,并在循环条件中写入 while( i + 1 < l ) 即可。

这是一个稍微改进的版本:

def sort(a: Array[Int]) {
  var l = a.length
  var switchesLeft = true

  while(switchesLeft) {

    switchesLeft = false
    for(i <- 0 until l-1 if a(i) > a(i+1)){
      // Switch the elements
      val t = a(i+1)
      a(i+1) = a(i)
      a(i) = t

      switchesLeft = true
    }
  }
}

The reason for cycling is if( x == l ) x = 0. Leave it out, and write while( i + 1 < l ) for the loop condition, then it works.

Here is a slightly improved version:

def sort(a: Array[Int]) {
  var l = a.length
  var switchesLeft = true

  while(switchesLeft) {

    switchesLeft = false
    for(i <- 0 until l-1 if a(i) > a(i+1)){
      // Switch the elements
      val t = a(i+1)
      a(i+1) = a(i)
      a(i) = t

      switchesLeft = true
    }
  }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文