1.什么是选择排序
选择排序-把数组分为2个区域,已排序区,和未排序区域,默认从第i开始,依次和i++未排序区域数组元素比较,找到未排序区最小元素的与之交换。
2.算法代码
/**
* 选择排序-把数组分为2个区域,已排序区,和未排序区域
* 默认从第0开始,依次和未排序区域数组元素比较,找到未排序区最小元素的与之交换
* @Author zy_ytx
* @Date 2022/1/10 14:28
* @Param
* @Return
* @Exception
*/
public static void selectionSort_1(int[] arr){
//比较循环的次数 arr.length -1
for (int i = 0; i < arr.length-1; i++) {
//单次比较最小值索引,默认i
int mIndex=i;
//默认从第(i+1)开始,依次和未排序区域数组元素比较,找到未排序区最小元素的与之交换
for (int j = i+1; j < arr.length; j++) {
System.out.printf("selectionSort_1 ==> 内循环比较次数:" + j + "\n\r");
if(arr[mIndex] > arr[j]){
mIndex = j;
}
}
//只有当前最小值index不等于i才进行交换
if(mIndex != i){
swap(arr,mIndex,i);
}
System.out.printf("selectionSort_1 ==> arr:" + Arrays.toString(arr) + "\n\r");
}
}
打印输出
selectionSort_1 ==> 内循环比较次数:1
selectionSort_1 ==> 内循环比较次数:2
selectionSort_1 ==> 内循环比较次数:3
selectionSort_1 ==> 内循环比较次数:4
selectionSort_1 ==> 内循环比较次数:5
selectionSort_1 ==> 内循环比较次数:6
selectionSort_1 ==> 内循环比较次数:7
selectionSort_1 ==> 内循环比较次数:8
selectionSort_1 ==> arr:[1, 4, 2, 5, 7, 9, 3, 21, 10]
selectionSort_1 ==> 内循环比较次数:2
selectionSort_1 ==> 内循环比较次数:3
selectionSort_1 ==> 内循环比较次数:4
selectionSort_1 ==> 内循环比较次数:5
selectionSort_1 ==> 内循环比较次数:6
selectionSort_1 ==> 内循环比较次数:7
selectionSort_1 ==> 内循环比较次数:8
selectionSort_1 ==> arr:[1, 2, 4, 5, 7, 9, 3, 21, 10]
selectionSort_1 ==> 内循环比较次数:3
selectionSort_1 ==> 内循环比较次数:4
selectionSort_1 ==> 内循环比较次数:5
selectionSort_1 ==> 内循环比较次数:6
selectionSort_1 ==> 内循环比较次数:7
selectionSort_1 ==> 内循环比较次数:8
selectionSort_1 ==> arr:[1, 2, 3, 5, 7, 9, 4, 21, 10]
selectionSort_1 ==> 内循环比较次数:4
selectionSort_1 ==> 内循环比较次数:5
selectionSort_1 ==> 内循环比较次数:6
selectionSort_1 ==> 内循环比较次数:7
selectionSort_1 ==> 内循环比较次数:8
selectionSort_1 ==> arr:[1, 2, 3, 4, 7, 9, 5, 21, 10]
selectionSort_1 ==> 内循环比较次数:5
selectionSort_1 ==> 内循环比较次数:6
selectionSort_1 ==> 内循环比较次数:7
selectionSort_1 ==> 内循环比较次数:8
selectionSort_1 ==> arr:[1, 2, 3, 4, 5, 9, 7, 21, 10]
selectionSort_1 ==> 内循环比较次数:6
selectionSort_1 ==> 内循环比较次数:7
selectionSort_1 ==> 内循环比较次数:8
selectionSort_1 ==> arr:[1, 2, 3, 4, 5, 7, 9, 21, 10]
selectionSort_1 ==> 内循环比较次数:7
selectionSort_1 ==> 内循环比较次数:8
selectionSort_1 ==> arr:[1, 2, 3, 4, 5, 7, 9, 21, 10]
selectionSort_1 ==> 内循环比较次数:8
selectionSort_1 ==> arr:[1, 2, 3, 4, 5, 7, 9, 10, 21]
算法很简单,外层比较次数为 arr.length -1,从i开始与i++位置元素比较,找到未排序区域最小值,进行交换,进行( arr.length -1) 循环处理,数组完成排序。
3.总结
- 时间复杂度 -O(n^2)
- 最好情况 - O(n^2)
- 最坏情况 - O(n^2)
- 空间复杂度 - 只有一个交换临时变量temp,O(1)
- 非稳定算法(多次重排无法保证重复元素的相对位置一一致)