選擇排序是每次循環(huán)都從未被選擇的數(shù)組中選取一個(gè)最小值放在數(shù)組前面。第一次循環(huán)將全部數(shù)組中的最小值放在下標(biāo)為0的位置,此時(shí),下標(biāo)為0的數(shù)被視為已被選擇數(shù)組;第二次循環(huán)將從未被選擇的數(shù)組從選出第二最小值放在下標(biāo)為1的位置……由此循環(huán)到數(shù)組中不包含未被選擇的數(shù)為止。
歸并排序的最好、最壞和平均時(shí)間復(fù)雜度都是O(n^2)。
/**
* Created by lkmc2 on 2018/1/8.
*/
public class SelectSort {
public static void selectSort(int[] array) {
for (int i = 0; i < array.length; i++) {
//標(biāo)簽當(dāng)前下標(biāo)為最小值下標(biāo)
int min = i;
//從i下標(biāo)的后一位到數(shù)組最后一位選出最小值的下標(biāo)
for (int j = i + 1; j < array.length; j++)
if (array[j] < array[min])
min = j;
//將最小值的下標(biāo)與i位置的值交換
int temp = array[i];
array[i] = array[min];
array[min] = temp;
}
}
public static void main(String[] args) {
int[] array = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1};
selectSort(array);
for (int num : array) {
System.out.print(num + " ");
}
}
}
運(yùn)行結(jié)果