Scala 过程陷入无限循环(我认为)
以下代码是数组排序算法的手动版本,获取任何整数数组,并更改该数组,使其处于非递减顺序。由于某种原因,当我在数组上调用这个过程时,我的 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
循环的原因是
if( x == l ) x = 0
。省略它,并在循环条件中写入 while( i + 1 < l ) 即可。这是一个稍微改进的版本:
The reason for cycling is
if( x == l ) x = 0
. Leave it out, and writewhile( i + 1 < l )
for the loop condition, then it works.Here is a slightly improved version: