个人理解:
每次找到当前查找数组的最小值,并替换位置
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);
}
}