I'm trying to implement bubblesort using arrays but am having a tough time doing so. Here's what I have so far:
fun swap(A, i, v) =
let
val temp = sub(A, i);
in
update(A, i, sub(A, v));
update(A, v, temp)
end;
This takes constant time so all good so far.
exception Empty;
fun bubbleSort(nil, i) = raise Empty
(* if has one element, already sorted)
| bubbleSort(
(* if at least two elements, compare *)
| bubbleSort(A, i) =
if i < A.length then
if sub(A, i) > sub(A, i+1) then
swap(A, i, i+1)
else bubbleSort(i+1);
1) Now, this will only go through an array of >= 2 elements once. But the bubblesort algorithm continues until you no longer need to swap elements and I'm not sure how to implement that recursively.
2) How do we pattern match on an array of length 1? With a list it'd just be bubbleSort([x])
...
Any help implementing would be awesome, bclayman
To answer your first question, one approach would be to add an extra parameter to your bubbleSort
function which determines whether or not you have reached a fixed point. Your function will then have the following type
bubbleSort : int Array -> int -> bool -> int Array
In each iteration, if you actually perform a swap, then set the flag to true. Once you have gone through the entire array, then check if the flag has been set, and if so, reset i
to 0. Keep repeating this process until you make it all the way through without setting the flag.
Pattern matching on arrays is not something that is typically done, you can do it for vectors (see this link, note that this is SML/NJ specific), however, you are probably better of just using the length function instead. This way, there isn't even any need to split up your first two cases. You can simply check is the length less than 1, and if so, return the array without doing any swaps.