我在一本书上看到过:
BubbleSort( list )
length <-- lenght of list
do {
swapped_pair <-- false
index <-- 1
while index <= length - 1 {
if list[index] > list[index + 1] {
swap( list[index], list[index + 1] )
swapped_pair = true
index <-- index + 1
}
}
} while( swapped = true )
end
在上面的伪代码中,索引只增加if list[index] > list[index + 1]
,因为index <-- index + 1
在if循环内。
所以if list[index] > list[index + 1]
不为真,那么接下来的行是:
swap( list[index], list[index + 1] )
swapped_pair = true
index <-- index + 1
不会被执行。包括index <-- index + 1
这将导致如果前两个变量被正确排序,那么代码将不会检查后面两个变量,因为在这种情况下index不会增加。
然后while index <= length - 1
将永远为真,因为索引永远不会增加,并且代码可能会卡在while index <= length - 1
循环中。
索引不应该放在if循环之外吗?
:
BubbleSort( list )
length <-- lenght of list
do {
swapped_pair <-- false
index <-- 1
while index <= length - 1 {
if list[index] > list[index + 1] {
swap( list[index], list[index + 1] )
swapped_pair = true
}
index <-- index + 1
}
} while( swapped = true )
end
因此if list[index] > list[index + 1]
然后它们被交换,交换对设置为true。如果if list[index] > list[index + 1]
不为真,则使用index <-- index + 1
将索引增加1。
由于while-loop仍然在继续,因为index <= length - 1
,从IF
开始的过程将不断重复,直到索引0和1到索引n-1和1。
我的伪代码版本正确吗?
你是正确的。内部while循环中的条件需要在每次迭代后改变。