为什么这个标准 ML 冒泡排序的循环只执行一次?

Why does this Standard ML bubblesort's loop only execute once?

所以我尝试使用 ML 的引用类型来实现 bubblesort。我编译了 Poly/ML 中的代码,似乎 "while(!flag)" 循环对任何输入只执行一次。

例如:[2,3,1] 得到 "sorted" 到 [2,1,3],即第一个循环有效但第二个循环没有 运行.

"Flag up" 打印了一次。

怎么了?

谢谢。

fun bubbleSort l =        (* l being a list of references *)
let
    val it = ref 0        (* iterator variable *)
    val len = length l
    val flag = ref true   (* to be set to true when a swap is made *)
in
    while (!flag) do
    (
        flag := false;
        while ((!it) < (len-1)) do
        (
            if (get l (!it)) > (get l ((!it)+1))
            then (swap_next l (!it); flag := true; TextIO.print "Flag up\n")
            else ();
            it := (!it) + 1
        )
    )
end;

如果需要,可以找到我编写的模块的完整代码here

Bubblesort 重复扫描同一个数组。您的内部循环只扫描一次但永远不会重置计数器 it。行前

while ((!it) < (len-1)) do

你应该把线

it := 0;