本博客将简要介绍选择排序。
定义
选择排序(英语:Selection sort)是一种简单直观的排序算法。它的工作原理是:每次找出第 i 小的元素(也就是 Ai..n 中最小的元素),然后将这个元素与数组第 i 个位置上的元素交换。
性质
稳定性
由于 swap(交换两个元素)操作的存在,选择排序是一种不稳定的排序算法。
时间复杂度
选择排序的最优时间复杂度、平均时间复杂度和最坏时间复杂度均为 O(n 2)。
代码实现
伪代码
1 Input. An array A consisting of n elements.
2 Output. A will be sorted in nondecreasing order.
3 Method.
4 for i ← 1 to n − 1
5 ith ← i
6 for j ← i + 1 to n
7 if A[j] < A[ith]
8 ith ← j
9 swap A[i] and A[ith]
C++
// C++ Version
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]);
}
}
Python:
# Python Version
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]