選擇排序的概念就是從未排序中選擇最小的元素放入到已排序元素的最后面。
下面是對一組整數進行排序。
1 public class selectionSort { 2 public static void main(String[] args){ 3 int[] toBeSorted = {1,54,3,8,6,0}; 4 5 6 for(int i = 0; i < toBeSorted.length; i++){ 7 for(int j = i+1; j < toBeSorted.length; j++){ 8 if(toBeSorted[i] > toBeSorted[j]){ 9 int temp = toBeSorted[i]; 10 toBeSorted[i] = toBeSorted[j]; 11 toBeSorted[j] = temp; 12 } 13 } 14 } 15 16 for(int i = 0; i <toBeSorted.length; i++){ 17 System.out.print(toBeSorted[i]+" "); 18 } 19 20 } 21 22 }
但是這種方法的效率不高。
原因如下:如果你要排序的數字是:2,4,6,7,3,5,1,9,8
當i=1的時候,4要與后面的3進行交換,然后與1再進行交換,這樣進行兩次交換就降低了效率。如果加上兩個變量便會去除不必要的交換。代碼如下:
public class selectionSort { public static void main(String[] args){ int[] toBeSorted = {1,54,3,8,6,0}; //k記錄當前已排完序的最后一個元素的位置, //temp用於交換時候的臨時變量 //為了避免每次都要重新申請內存,所以將兩個變量提出來放在函數外面 int k, temp; for(int i = 0; i < toBeSorted.length; i++){ k = i; for(int j = k+1; j < toBeSorted.length; j++){ if(toBeSorted[k] > toBeSorted[j]){ k = j; } } if(k != i){ temp = toBeSorted[i]; toBeSorted[i] = toBeSorted[k]; toBeSorted[k] = temp; } } for(int i = 0; i <toBeSorted.length; i++){ System.out.print(toBeSorted[i]+" "); } } }
最后來分析一下算法的復雜度:O(n*n)的。這是因為算法要進行循環排序。
這就意味值在n比較小的情況下,算法可以保證一定的速度,當n足夠大時,算法的效率會降低。並且隨着n的增大,算法的時間增長很快。因此使用時需要特別注意。