int nums = [2,4,7,3,9,1,0,4];
- 第一次遍历 开始下标为 0 , 最小值下标为 6 , 将 下标为6 的 与 下标为 0 的数组互换
交换后数组为 : [0,4,7,3,9,1,2,4]
- 第二次遍历 从 下标为 1 开始往后遍历 , 最小值 下标为 5 , 将下标为 5 的与 下标为 1 的互换
交换后的数组为 : [0,1,7,3,9,4,2,4]
- 重复以上操作 最终得到
[0,1,2,3,4,4,7,9]
/**
* 选择排序
*
* 思路:
* 1.遍历以此数组 , 获取数组中最小值的下标
*
* 2.将最小值的 和遍历的数组的第 i 个位置 交换
*
* 3.重复 1,2操作
*
*
*/
public class SelectionSort {
public static int[] selectionSortFun(int[] nums){
if (nums == null || nums.length == 0) {
throw new IllegalArgumentException("数组为空");
}
int length = nums.length;
for (int i = 0; i < length; i++) {
int minIndex = i ;
for (int j = i + 1; j < length; j++) {
if (nums[minIndex] > nums[j]) {
minIndex = j;
}
}
int a = nums[i];
nums[i] = nums[minIndex];
nums[minIndex] = a ;
}
return nums;
}
public static void main(String[] args) {
int[] nums = RandomBase.random(10, 2, 50);
System.out.println(Arrays.toString(nums));
System.out.println(Arrays.toString(selectionSortFun(nums)));
}
}