简体   繁体   English

标准ML:带有数组的BubbleSort

[英]Standard ML: BubbleSort with Arrays

I'm trying to implement bubblesort using arrays but am having a tough time doing so. 我正在尝试使用数组来实现Bubblesort,但是这样做很难。 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. 1)现在,这将仅通过> = 2个元素的数组一次。 But the bubblesort algorithm continues until you no longer need to swap elements and I'm not sure how to implement that recursively. 但是Bubblesort算法一直持续到您不再需要交换元素并且我不确定如何递归实现该方法为止。

2) How do we pattern match on an array of length 1? 2)如何在长度为1的数组上进行模式匹配? With a list it'd just be bubbleSort([x]) ... 有了列表,它只会是bubbleSort([x]) ...

Any help implementing would be awesome, bclayman 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. 为了回答您的第一个问题,一种方法是在bubbleSort函数中添加一个额外的参数,该参数确定您是否已达到固定点。 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. 在每次迭代中,如果您实际执行交换,则将标志设置为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. 遍历整个数组后,请检查是否已设置标志,如果已设置,则将i重置为0。继续重复此过程,直到完全完成操作而不设置标志。

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. 通常无法完成对数组的模式匹配,您可以对向量进行匹配(请参阅链接,请注意,这是SML / NJ特定的),但是,最好只使用长度函数。 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. 您可以简单地检查长度是否小于1,如果是,则返回数组而不进行任何交换。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM