动图:
核心在于,每一次内层遍历都将最小的数挑出来放在序列的最前面。
每一次都是选的最小数,所以称为选择排序。
代码:
public class SelectSort {
public static void main(String[] args){
int[] nums = new int[]{ 8, 9, 1, 7, 2, 3, 5, 4, 6, 0 };
int[] res = sort(nums);
for(int i=0; i<res.length; i++){
System.out.print(res[i] + " ");
}
}
public static int[] sort(int[] nums){
if(nums == null){
throw new RuntimeException("数组为空");
}
int temp;
for(int i = 0;i < nums.length - 1;i++){
int minIndex = i; // 假定最开始的元素就是最小
for(int j = i + 1;j < nums.length;j++){
if(nums[minIndex] > nums[j]){
minIndex = j;
}
}
temp = nums[i];
nums[i] = nums[minIndex];
nums[minIndex] = temp;
}
return nums;
}
}