简单的selectionSort无法正常工作
这里doSort方法不起作用只是因为操纵for循环内部的“最小”,有人能告诉我什么是根本原因,我无法理解根本原因
object SelectionSort extends App {
val unSortedArray = ArrayBuffer(5, -1, 8, 4, 6, 21, 4, 5, -0, 0)
def doSort (ary: ArrayBuffer[Int], startIndex: Int, endIndex: Int) = {
var minimum = 0
for {
index <- startIndex to endIndex
_ = minimum = ary(index)
loopIndex <- index until endIndex
} {
if (minimum > ary(loopIndex + 1)) {
minimum = ary(loopIndex + 1)
val swap = ary(index)
ary(index) = ary(loopIndex + 1)
ary(loopIndex + 1) = swap
}
}
}
def doSortWorking (ary: ArrayBuffer[Int], startIndex: Int, endIndex: Int) = {
var minimum = 0
for {
index <- startIndex to endIndex
loopIndex <- index until endIndex
} {
minimum = ary(index)
if (minimum > ary(loopIndex + 1)) {
minimum = ary(loopIndex + 1)
val swap = ary(index)
ary(index) = ary(loopIndex + 1)
ary(loopIndex + 1) = swap
}
}
}
doSort(unSortedArray, 0, unSortedArray.size - 1)
println(unSortedArray)
doSortWorking(unSortedArray, 0, unSortedArray.size - 1)
println(unSortedArray)
}
答案 0 :(得分:1)
只需在doSort()中交换第二行和第三行进行理解:
def doSort (ary: ArrayBuffer[Int], startIndex: Int, endIndex: Int) = {
var minimum = 0
for {
index <- startIndex to endIndex
loopIndex <- index until endIndex
_ = minimum = ary(index)
} {
if (minimum > ary(loopIndex + 1)) {
minimum = ary(loopIndex + 1)
val swap = ary(index)
ary(index) = ary(loopIndex + 1)
ary(loopIndex + 1) = swap
}
}
}
在doSortWorking函数内找到loopIndex后,您应该将新值重新指定为最小值。
编辑:为什么您的doSort版本不起作用?
让我们试试它的简化版本:
scala> val startIndex = 0
firstIndex: Int = 0
scala> val endIndex = 3
lastIndex: Int = 3
scala> var minimum = 0
minimum: Int = 0
scala> for {
| index <- startIndex to endIndex
| _ = minimum = index
| } {
| println(minimum)
| }
3
3
3
3
为什么不打印0 1 2 3
?因为理解不像你在这里想象的那样有效。检查这个答案:https://stackoverflow.com/a/3754568/5053865这里有一些关于for-comprehension评估的规则。让我们应用它们:
scala> for ((p, _) <-
| for (index <- startIndex to endIndex)
| yield { val x0 = minimum = index; (index, x0) }
| ) {
| println(minimum)
| }
3
3
3
3
scala> startIndex to endIndex map {
| index => val x0 = minimum = index; (index, x0)
| } foreach {
| _ => println(minimum)
| }
3
3
3
3
现在你应该看看这里到底发生了什么。首先,将startIndex和endIndex中的值分配给变量minimum,然后每次都使用maximum = endIndex执行body!