[JAVA数据结构]选择排序

        选择排序,在一个数组从选出最大值和最小值,再分别放置到数组的两端,不断缩小范围重复进行。

         此排序比较简单,直接上代码:

    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));
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_67719939/article/details/130631794