[JAVA data structure] selection sort

        Selection sorting is to select the maximum value and minimum value from an array, and then place them at both ends of the array, and repeat the process continuously narrowing the range.

         This sorting is relatively simple, directly on the code:

    public static void swap(int[] array,int a,int b){
        int tmp = array[a];
        array[a] = array[b];
        array[b] = tmp;
    }
    public static void selectSort(int[] array){
        int left = 0;
        int right = array.length - 1;
        while(left < right){
            int minIndex = left;//
            int maxIndex = left;//假设最小值和最大值的下标为left
            for(int i = left + 1; i < right; i++){
                if(array[i] < array[minIndex]){
                    //遇到一个更小的就交换
                    minIndex = i;
                }
                if(array[i] > array[maxIndex]){
                    maxIndex = i;
                }
            }
            swap(array,left,minIndex);
            //这里有一个特殊情况,就是如果范围内的最大值在left的位置,第一次交换之后
            //left的位置就会变成最小值,此时就不是最大值了
            //所以,如果最大值的位置在left的话,可以将maxIndex = minIndex
            //交换后,原本在left的值就到了minIndex的位置上
            if(maxIndex == left){
                maxIndex = minIndex;
            }
            swap(array,right,maxIndex);
            //确定了此范围了两端后,可以缩小范围
            left++;
            right--;
        }
    }
    public static void main(String[] args) {
        int[] array = {12,89,2,4,61,50};
        selectSort(array);
        System.out.println(Arrays.toString(array));
    }
}

Guess you like

Origin blog.csdn.net/weixin_67719939/article/details/130631794