代码实现
package com.atguigu.sort;
import java.util.Arrays;
/**
* @author WHT
* @create 2021-06-16 8:40
*/
public class SelectSort {
public static void main(String[] args) {
int[] arr = {101, 34, 119, 1};
System.out.printf("排序前的数组:");
System.out.println(Arrays.toString(arr));
selectSort(arr);
}
// 【王】 比视频方法少创建一个min变量。
public static void selectSort(int[] arr) {
for (int i = 0; i < arr.length - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < arr.length; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
// 判断是否交换。
if (minIndex != i) {
int temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
System.out.printf("第%d轮后的数组:", i + 1);
System.out.println(Arrays.toString(arr));
}
}
}
运行结果
D:\java\jdk-11.0.11\bin\java.exe "-javaagent:D:\IntelliJ IDEA 2020.1.1\lib\idea_rt.jar=7737:D:\IntelliJ IDEA 2020.1.1\bin" -Dfile.encoding=UTF-8 -classpath E:\WHT\Project\Java\DataStructures\out\production\DataStructures com.atguigu.sort.SelectSort
排序前的数组:[101, 34, 119, 1]
第1轮后的数组:[1, 34, 119, 101]
第2轮后的数组:[1, 34, 119, 101]
第3轮后的数组:[1, 34, 101, 119]
Process finished with exit code 0
8万随机数测试:6s 。