選擇排序的步驟如下迅诬。
(1) 從左至右檢查數(shù)組的每個格子佩谷,找出值最小的那個旁壮。
在此過程中,用一個變量來記住檢查過的數(shù)字的最小值(事實上記住的是索引)谐檀。
如果一個格子中的數(shù)字比記錄的最小值還要小抡谐,就把變量改成該格子的索引
(2) 每一輪檢查完,知道哪個格子的值最小之后桐猬,將該格與本輪檢查的起點交換麦撵。
第 1 輪檢查的起點是索引 0,第 2 輪是索引 1溃肪,以此類推免胃。
冒泡排序直接比較交換未排序的相鄰的兩個值;而選擇排序先檢查未排序的起始索引值與其它值(記錄最小值索引)惫撰,檢查完畢之后再將起始值與最小值進(jìn)行交換(每一輪檢查交換結(jié)束羔沙,最小值總是在起始位值)。
在完全逆序的情況下厨钻,冒泡排序每一輪的每一次檢查之后都要做交換元素的動作扼雏,而選擇排序則在每一輪檢查完畢之后再進(jìn)行元素的交換。
冒泡排序和選擇排序比較
package com.sort;
/**
* @author: jk
* @since: 2020-03-20 01:10
* <p>
* 選擇排序
* </p>
**/
public class selection_sort {
public static void main(String[] args) {
int[] list = {65, 55, 45, 35, 25, 15, 10};
// int[] sortList = selectionSort(list);
int[] sortList = selectionSort2(list);
for (int i = 0; i < sortList.length; i++) {
System.out.println(sortList[i]);
}
}
private static int[] selectionSort(int[] array){
for (int i = 0; i < array.length; i++) {
// 1 記住最小值的索引
int lowestIndex = i;
// 2 將array[i] 與它后面的所有元素比較
for (int j = i + 1; j < array.length; j++) {
// 將 lowestIndex 更新為最小值的索引
if (array[j] < array[lowestIndex]){
lowestIndex = j;
}
}
// 3 比較完之后莉撇,如果 lowestIndex 有更新呢蛤,則交換元素
if (lowestIndex != i){
int temp = array[i];
array[i] = array[lowestIndex];
array[lowestIndex] = temp;
}
}
// 4 循環(huán)完畢,即排序完成棍郎。
return array;
}
}