個人理解:
每次找到當前查找數組的最小值,並替換位置
package com.example;
import java.util.Arrays;
public class SelectionSort {
private static void sort(int [] array){
System.out.println("遍歷前: " + Arrays.toString(array));
for (int i = 0; i < array.length; i++) {
// 因爲每一次循環, 都會把當前最小的值放在前面, 所以最小值的下標從循環下標開始
int currentMinIndex = i;
int currentMinNumber = array[i];
System.out.println("判斷前, index = " + i + "\t currentMinNumber = " + currentMinNumber);
// j = i + 1 是因爲當前最小的值已經是array[i]當前下標對應的值了, 所以要進行判斷的話只需要驗證後面的即可。
for (int j = i + 1; j < array.length; j++) {
// 當 當前最小值大於當前值時, 需要替換最小值與最小值目前下標
if(currentMinNumber > array[j]){
currentMinNumber = array[j];
currentMinIndex = j;
}
}
System.out.println("判斷後, index = " + currentMinIndex + "\t currentMinNumber = " + currentMinNumber);
// 如果index值發生改變,說明存在比當前數值還小的值。
// 先將找到的最小值的位置換成當前值, 然後將當前值的位置替換成當前最小值
if(currentMinIndex != i){
array[currentMinIndex] = array[i];
array[i] = currentMinNumber;
}
System.out.println(Arrays.toString(array));
}
System.out.println("遍歷後: " + Arrays.toString(array));
}
public static void main(String[] args) {
int [] array = {999, 55, 88, 99, 5, 8888, 57};
sort(array);
}
}