Two versions of selection sort

风流意气都作罢 提交于 2019-12-11 18:50:59

问题


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:


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.



来源:https://stackoverflow.com/questions/24878026/two-versions-of-selection-sort

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!