跳转至

選擇排序

本頁面將簡要介紹選擇排序。

定義

選擇排序(英語:Selection sort)是一種簡單直觀的排序算法。它的工作原理是每次找出第 \(i\) 小的元素(也就是 \(A_{i..n}\) 中最小的元素),然後將這個元素與數組第 \(i\) 個位置上的元素交換。

selection sort animate example

性質

穩定性

由於 swap(交換兩個元素)操作的存在,選擇排序是一種不穩定的排序算法。

時間複雜度

選擇排序的最優時間複雜度、平均時間複雜度和最壞時間複雜度均為 \(O(n^2)\)

代碼實現

偽代碼

\[ \begin{array}{ll} 1 & \textbf{Input. } \text{An array } A \text{ consisting of }n\text{ elements.} \\ 2 & \textbf{Output. } A\text{ will be sorted in nondecreasing order.} \\ 3 & \textbf{Method. } \\ 4 & \textbf{for } i\gets 1\textbf{ to }n-1\\ 5 & \qquad ith\gets i\\ 6 & \qquad \textbf{for }j\gets i+1\textbf{ to }n\\ 7 & \qquad\qquad\textbf{if }A[j]<A[ith]\\ 8 & \qquad\qquad\qquad ith\gets j\\ 9 & \qquad \text{swap }A[i]\text{ and }A[ith]\\ \end{array} \]
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
void selection_sort(int* a, int n) {
  for (int i = 1; i < n; ++i) {
    int ith = i;
    for (int j = i + 1; j <= n; ++j) {
      if (a[j] < a[ith]) {
        ith = j;
      }
    }
    std::swap(a[i], a[ith]);
  }
}
1
2
3
4
5
6
7
def selection_sort(a, n):
    for i in range(1, n):
        ith = i
        for j in range(i + 1, n + 1):
            if a[j] < a[ith]:
                ith = j
        a[i], a[ith] = a[ith], a[i]
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
// arr代碼下標從 1 開始索引
static void selection_sort(int[] arr, int n) {
    for (int i = 1; i < n; i++) {
        int ith = i;
        for (int j = i + 1; j <= n; j++) {
            if (arr[j] < arr[ith]) {
                ith = j;
            }
        }
        // swap
        int temp = arr[i];
        arr[i] = arr[ith];
        arr[ith] = temp;
    }
}