选择排序
选择排序是从无序数列中选择最小(大)的一个放到有序区的最后面
相比冒泡排序方法而言,减少了大量的交换。
上代码
public static void selectionsort(int[] array) {
for (int i = 0; i < array.length - 1; i++) {
int minIndex = i;//默认无序区第一个为最小值
for (int j = i + 1; j < array.length; j++) {
if (array[j] < array[minIndex]) {//在无序区中挑出最小值
minIndex = j;
if (i != minIndex) {//如果和无序区默认的最小值不一样,证明无序区中的最小值交换过
int temp = array[i];
array[i] = array[minIndex];
array[minIndex] = temp;
}
}
}
}
}
public static void main(String[] args) {
int[] array = new int[]{3, 4, 2, 1, 5, 6, 7, 8, 30, 50, 1,
33, 24, 5, -4, 7, 0};
selectionsort(array);
System.out.println(Arrays.toString(array));
}
时间复杂度:每一轮选择最小值所用的时间复杂度是n,一共迭代n-1轮,所以总的时间复杂度是O(n2)
空间复杂度:原地排序,空间复杂度是O(1)
选择排序是一个不稳定的排序算法