Two versions of selection sort

2019-09-19 08:19发布

Recently i have been looking into sorting algorithms, and like many intro to algorithms books the one I have begun to read starts off with a selection sort implementation. the code went as follows...

Implementation A

//a is an array of ints.
int n = a.length;
    for(int i = 0; i < n; i ++){
        int min =0;
        for( int x = i+1; x <n;x++){
            if(a[x].compareTo(a[i])<0){
                Comparable tmp = a[i];
                a[i] = a[x];
                a[x] = tmp;                 
            }
        }
    }

After analyzing the code block i altered the algorithm to the following.

Implementation B

//a is an array of ints
int n = a.length;
    for(int i = 0; i < n; i ++){
        int min =i;
        for( int x = i+1; x <n;x++){
            if(a[x].compareTo(a[min])<0){
                        min=x;      
            }
        }

        if(min>i){
            Comparable tmp = a[i];
            a[i] = a[min];
            a[min] = tmp;
        }

    }

I have also found similar implementations online using the min value to locate the smallest value within the array and then swapping it out with the item in position i of the array. My question, Is there something incorrect with the second implementation? is this not a proper selection sort because it is not swapping out every element it locates that is smaller then the item at position i, but instead waits till it finds the smallest item in the array prior to swapping?

I have run some tests with both algorithms with over 10000 array values and the second implementation always finishes first, by almost double the speed. These tests were on randomized arrays.

1条回答
疯言疯语
2楼-- · 2019-09-19 09:02

Implementation B is a correct Selection Sort. Implementation A is not because it always swap smaller value into the front which sometimes is not smallest value.

According to wikipedia http://en.wikipedia.org/wiki/Selection_sort

The algorithm proceeds by finding the smallest (or largest, depending on sorting order) element in the unsorted sublist, exchanging it with the leftmost unsorted element (putting it in sorted order), and moving the sublist boundaries one element to the right.

查看更多
登录 后发表回答