直接選擇排序是一種簡單的排序方法,它每次從當前待排序的區間中選擇出最小的元素,把該元素與該區間的第一個元素交換。
第一次從a[0]~a[n-1]中選取最小值,與a0]交換,第二次從a[1]~a[n-1]中選取最小值,與a[1]交換,....,第i次從a[i-1]~a[n-1]中選取最小值,與a[i-1]交換,.....,第n-1次從a[n-2]~a[n-1]中選取最小值,與a[n-2]交換,總共通過n-1次,得到一個按排序碼從小到大排列的有序序列。
例如:假定n = 8,數組a中8個元素的排序碼為:
(36,25,48,12,65,43,20,58)
如圖給出了進行每次選擇並交換后各排序碼位置的變動情況,中括號中為待排序區間,中括號前面為已經排好的元素。

直接選擇排序的算法用java描述為:
1 public static void selectionSort(int[] a,int n) { 2 if(n>a.length) { 3 System.out.println("超出數組長度"); 4 System.exit(1); 5 } 6 for (int i = 1; i < n; i++) { //i表示次數,共進行n-1次選擇和交換 7 int minIndex = i-1; //用minIndex表示最小元素的下標 8 for (int j = i; j < n; j++) {//找到當前排序區間中最小元素的下標 9 if(a[minIndex]>a[j]) {//如果后面的元素小於當前最小元素,則用minIndex記錄下后面最小元素的下標 10 minIndex = j; 11 } 12 } 13 if(minIndex != i) {//如果minIndex==i,說明minIndex就是當前排序區間首位元素的下標,因此不用交換 14 int temp = a[i]; 15 a[i] = a[minIndex]; 16 a[minIndex] = temp; 17 } 18 } 19 }
完整代碼並測試:
1 import java.util.Scanner; 2 3 public class SelectionSort { 4 public static void selectionSort(int[] a,int n) { 5 if(n>a.length) { 6 System.out.println("超出數組長度"); 7 System.exit(1); 8 } 9 for (int i = 1; i < n; i++) { //i表示次數,共進行n-1次選擇和交換 10 int minIndex = i-1; //用minIndex表示最小元素的下標 11 for (int j = i; j < n; j++) {//找到當前排序區間中最小元素的下標 12 if(a[minIndex]>a[j]) {//如果后面的元素小於當前最小元素,則用minIndex記錄下后面最小元素的下標 13 minIndex = j; 14 } 15 } 16 if(minIndex != i-1) {//如果minIndex==i-1,說明minIndex就是當前排序區間首位元素的下標,因此不用交換 17 int temp = a[i-1]; 18 a[i-1] = a[minIndex]; 19 a[minIndex] = temp; 20 } 21 } 22 } 23 24 public static void main(String[] args) { 25 Scanner input = new Scanner(System.in); 26 System.out.println("請輸入元素的個數"); 27 int n = input.nextInt(); 28 int[] a = new int[n]; 29 System.out.println("請依次輸入元素"); 30 for (int i = 0; i < a.length; i++) { 31 a[i] = input.nextInt(); 32 } 33 System.out.println("請輸入待排元素的個數"); 34 int m = input.nextInt(); 35 selectionSort(a,m); 36 System.out.println("排序之后"); 37 for (int i = 0; i < a.length; i++) { 38 System.out.print(a[i]+" "); 39 } 40 } 41 }
請輸入元素的個數
8
請依次輸入元素
36 25 48 12 65 43 20 58
請輸入待排元素的個數
8
排序之后
12 20 25 36 43 48 58 65
效率:
在直接選擇排序中,共需要進行n-1次選擇和交換,每次選擇需要比較n-i 次(1<=i<=n-1),每次交換最多需要3次移動,因此,總的比較次數:C=(n*n - n)/2,
總的移動次數(最大值): 3(n-1).由此可知,直接選擇排序的時間復雜度為 O(n^2)。由於在直接選擇排序中存在着前后元素之間的互換,因而可能會改變相同元素的前后位置,如4,3,4,2 第一次4和2交換,第一個4跑到了第3個4之后,所以此方法是不穩定的。
