核心過程
算是冒泡的一個(gè)簡(jiǎn)單優(yōu)化。
冒泡本質(zhì)是每次把最大的數(shù)放最后(或者最小的放最前)辰如。
那么每次都比較并交換相鄰的兩個(gè)數(shù)近上,不如直接選取最大數(shù)并和最后位置的數(shù)交換。
比較次數(shù)一樣宿饱,但是交換次數(shù)大大減少。
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;
}
}