排序原理:
1.每一次遍历的过程中,都假定第一个索引处的元素是最小值,和其他索引处的值依次进行比较,如果当前索引处的值大于其他某个素引处的值,则假定其他某个索引出的值为最小值,最后可以找到最小值所在的索引
2.交换第一个索引处和最小值所在的系引处的值
public class 选择排序 {
public static void main(String[] args) {
Integer[] arr = {4,5,6,2,7,9};
Selection.sort(arr);
System.out.println(Arrays.toString(arr));
}
static class Selection{
public static void sort(Comparable[] a){
// 外层循环确定有多少个元素参与排序->确定排序的轮数
for (int i = 0; i < a.length-1; i++) {
// 基于外层循环得到参与冒泡排序元素个数,挨个比较获取最小值索引
int minIndex = i;
for (int j = i+1; j < a.length; j++) {
if (greater(a[minIndex],a[j])){
minIndex = j;
}
}
// 交换值
exch(a,i,minIndex);
}
}
// 比较v是否大于w
public static boolean greater(Comparable v, Comparable w){
return v.compareTo(w)>0;
}
// 交换a中,i与j的位置
public static void exch(Comparable[] a, int i, int j){
Comparable temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}