java seven selection sort sort --3_

Select Sort:

Elements are divided into rows to be ordered and disordered interval section, the front section disorder, a maximum number of each selected array [max] interval from all elements of the disorder, the random number and the last section number exchanged (a number equivalent to the newly inserted in the first position ordered segment)
assuming all the elements are the disordered start interval:
java seven selection sort sort --3_java seven selection sort sort --3_
java seven selection sort sort --3_
continue to repeat the above operation
java seven selection sort sort --3_

The final result
java seven selection sort sort --3_
code implementation

public static void selectSort(int[] array) {//
//无序区间在前边
//每次选最大数
for (int i = 0; i < array.length - 1; i++) {
int max = 0;
for (int j = 1; j < array.length - i; j++) {
if (array[max] < array[j]) {
max = j;
}
}
swap(array, max, array.length-i- 1);
}

PS: Sort two-way choice

The basic idea is consistent with selection sort, but at the same time seeking to increase the maximum and minimum range of the method in the random, time-saving
code to achieve:

private static void selsectSorts2(int[] array){
        int low=0;
        int high=array.length-1;
        while(low<high){
            int max=low;
            int min=low;
            for(int i=low+1;i<=high;i++){
                if(array[i]>array[max]){
                    max=i;
                }
                if(array[i]<array[min]){
                    min=i;
                }
            }
            swap(array,min,low);
            if(max==low){//说明最大值就是第一个数
                max=min;//而刚上一步的交换,会将最大值交换到下标为min的位置
                        //所有要将max等于min,标记找回最大值
            }
            swap(array,max,high);
            low++;
            high--;
        }
    }

Guess you like

Origin blog.51cto.com/14234228/2434607