内存排序(二)——选择排序

核心过程

算是冒泡的一个简单优化。
冒泡本质是每次把最大的数放最后(或者最小的放最前)。
那么每次都比较并交换相邻的两个数,不如直接选取最大数并和最后位置的数交换。
比较次数一样,但是交换次数大大减少。

public static void selectionSortCore(int[] list, int begin, int end){
    int maxIndex = begin;
    for (int i = begin; i <= end; i++) {
        if(list[maxIndex] < list[i]){
            maxIndex = i;
        }
    }
    int temp = list[maxIndex];
    list[maxIndex] = list[end];
    list[end] = temp;
}

迭代过程

与冒泡同理。

public static void selectionSortIteration(int[] list){
    for (int i = list.length - 1; i >= 0 ; i--) {
        selectionSortCore(list, 0, i);
    }
}

合并两过程的写法

public static void selectionSort(int[] list){
    for (int i = list.length - 1; i >= 0 ; i--) {
        int maxIndex = 0;
        for (int j = 0; j <= i; j++) {
            if(list[maxIndex] < list[j]){
                maxIndex = j;
            }
        }
        int temp = list[maxIndex];
        list[maxIndex] = list[i];
        list[i] = temp;
    }
}

你可能感兴趣的:(内存排序(二)——选择排序)