Scala Procedure Stuck in Infinite Loop ( I think )
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 ) {
开发者_如何学Govar 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 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
}
}
}
精彩评论