So I tried to implement bubblesort using ML's reference types. I compiled the code in Poly/ML and it seems that the "while(!flag)" loop only executes once for any input.
For example: [2,3,1] gets "sorted" to [2,1,3], i.e. the first loop worked but the second never ran.
"Flag up" got printed once.
What's wrong?
Thanks.
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;
Full code of the module I wrote, if needed, can be found here.
Bubblesort repeatedly scans over the same array. Your inner loop scans over it just once but never resets the counter it
. Before the line
while ((!it) < (len-1)) do
You should put the line
it := 0;