选择算法
一、选择算法基本思路
假设数组arr一共有n个元素,则arr的长度length为n,每次遍历都将最小的元素放到最前面,第一次遍历从0到n-1,将最小的数放到0位置,第二次遍历从1到n-1(因为第一次已经把最小的数放在了0位置,所以不用再遍历第0位),将最小的放在1位置…
二、代码
```java
/**
* @author LJJIE
* on 2021/1/9 16:41
*/
public class SelectionSort {
public static void selectionSort(int[] arr){
int minLength = 2;
if (arr==null || arr.length<minLength){
return;//如果数组为空,或者数组只有两个元素就不用遍历;
}
for (int i=0; i<arr.length-1; i++){//最后一次遍历,只剩下一个元素了,这个元素必然是最大的元素,所以只遍历arr.length-2次;
int minIndex = i;//先默认本次遍历中最小的元素的角标为i;
for(int j=i+1; j<arr.length; j++){
minIndex = arr[minIndex] < arr[j]? j: minIndex;
//如果arr[j]更小,则最小的角标等于j;
swap(arr, minIndex, j);//交换
}
}
}
public static void swap(int[] arr, int minIndex, int j){
int temp = arr[minIndex];
arr[minIndex] = arr[j];
arr[j] = temp;
}
public static void main(String[] args) {
int[] arr = {1, 3, 48, 2, 56, 42};
System.out.println("排序前");
for (int a: arr) {
System.out.print(a+" ");
}
System.out.println();
System.out.println("排序后");
selectionSort(arr);
for (int a: arr){
System.out.print(a+" ");
}
}
}
三、时间复杂度
时间复杂度为O(n^2);