原理
- 将数组分为已排序和未排序的两部分
- 每次从未排序的中取出一个最小的放进已排序的
- 当选择至最后一次时,其实已经不用进行交换操作,因为最后一个数永远是最大的
选择的规律:
第0——length中最小的数与第0个数交换位置
第1——length中最小的数与第1个数换位置
第2——length中最小的数与第2个数交换位置
… …
第length - 1 —— length个与第i - 1个数进行比较
/**
* 选择排序
* 分为已排序和未排序的两部分
* 每次从未排序的中取出一个最小的放进已排序的
* 选择数组长度减一次,最后一个数永远是最大的
* @return
*/
public int[] selectionSort(int[] nums){
for (int i = 0; i < nums.length - 1; i++) {
// 最小的索引,从i——length - 1的区间中
int minIndex = i;
for (int j = i; j < nums.length; j++) {
if (nums[minIndex] > nums[j]) {
minIndex = j;
}
}
/*
* i代表每一轮选择到的最小元素要交换到的目标索引
* 最小的索引与索引为i的交换
*/
int temp = nums[i];
nums[i] = nums[minIndex];
nums[minIndex] = temp;
}
return nums;
}
@Test
public void selectionSortTest(){
int[] nums = {1,56,3,85,12,34,97,2,-89,4,33,77,66,22,11,0};
int[] ints = selectionSort(nums);
for (int anInt : ints) {
System.out.print(" "+anInt);
}
}