核心思想:在每轮循环中,找出该次循环中的最大数(或最小数)的索引,将该索引上的数与本次循环中数组最大索引上的数交换。
代码实现重点:
- 从后向前遍历数组,定义一个变量maxIndex记录该轮循环数组最大数的索引。
- 在最大索引前面(包含该索引)寻找该轮循环中最大数的索引,并通过赋值给maxIndex记录该索引位置。
- 将该轮循环中数组的最大索引与该轮循环中的最大数索引交换。
import java.util.Arrays;
public class selsectionsort {
private static int[] selectionSort(int[] arr){
for(int i=arr.length-1;i>0;i--){
//记录最大值的索引
int maxIndex=0;
//找到最大值的索引
for(int j=0;j<=i;j++){
if(arr[j]>arr[maxIndex]){
maxIndex=j;
}
}
swap(arr,i,maxIndex);
}
return arr;
}
private static void swap(int[] arr,int i,int j){
int temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
public static void main(String[] args){
int[] arr=new int[]{73,22, 93, 43, 55, 14, 28, 65, 39, 81};
selectionSort(arr);
System.out.println(Arrays.toString(arr));
}
}