jeudi 26 novembre 2015

Why the two implementations of random sort vary a lot in performance?

I need to implement a random sort, which is very bad at performance but just used to get used to random generating things:

I have two implementations:

public void sort(Integer[] a) {
    boolean sorted = false;
    boolean auxSorted = true;
    List<Integer> list = Arrays.asList(a);
    int n = a.length;

    while (sorted == false) {
        Collections.shuffle(list);

        int i = 0;
        while (i < n-1 && list.get(i) <= list.get(i + 1)) {
            i = i + 1;
        }
        if (i == n - 1) {
            sorted = true;
        }
    Integer[] sortedArray = new Integer[list.size()];
    a = list.toArray(sortedArray);
}

when I use an array of length 5 it gives correct answer very quickly, however I have another for loop version:

while (sorted == false) {
        Collections.shuffle(list);

        for(int i = 0; i < n-1; i++) {
            if(list.get(i) > list.get(i+1)) {
                auxSorted = false;
                break;
            }
        }

        if(auxSorted) {
            sorted = true;              
        }

    }

when I test with the same array it runs extremely slowly.

Are there any differences between the two implementations? To me I think the for loop version is actually more efficient in this context.




Aucun commentaire:

Enregistrer un commentaire