这个 BubbleSort 伪代码有什么错误吗? (或者我理解错了)?

Is there some error on this BubbleSort pseudocode? (or I'm taking it wrong)?

我在一本书上看到的:

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

这将导致如果前两个变量排序正确,则代码不会检查接下来的两个变量,因为在这种情况下索引不会增加。

然后 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 循环继续,因为仍然是 index <= length - 1,从 IF 开始的过程将一次又一次地重复,直到索引 0 和 1 到索引 n-1 和 1。

我的伪代码版本对吗?

你是对的。内部 while 循环中的条件需要有一种在每次迭代后改变的方式。