一、选择排序算法个人理解
- 如果有N个元素需要排序,首先从N个元素中找到最小的那个元素,然后与索引ix=0位置上的元素进行交换(如果没有比原来索引ix=0位置上的元素小就不用交换),接着再从剩下的N-1个元素中找出最小的元素,再与索引ix=1位置上的元素进行交换;之后,再从剩下的N-2个元素中找出最小的元素,再与索引ix=2位置上的元素进行交换,…重复上面的操作,一直到完全排序完成为止。具体排序过程见下图:
二、选择排序算法代码实现(C++版本)
#include "iostream"
using namespace std;
void printSequence(int a[], int size);
void selectSort(int a[], int size);
/* 选择排序 */
int main(){
const int SIZE = 7;
int a[SIZE] = {5, 7, 2, 8, 9, 1, 4};
cout << "选择排序前: ";
printSequence(a, SIZE);
selectSort(a, SIZE);
cout << "选择排序后: ";
printSequence(a, SIZE);
return 0;
}
void printSequence(int a[], int size){
for (int i = 0; i <= size - 1; i++){
cout << a[i] << " ";
}
cout << endl;
}
// 选择排序
void selectSort(int a[], int size){
int minIndex, temp;
for (int ix = 0; ix < size - 1; ix++){ // 通过外层for循环对索引进行遍历,保存最小元素所对应的索引
minIndex = ix; // 外层for循环开始循环时,将minIndex初始化为数组第一个元素的索引
for (int jx = ix + 1; jx < size; jx++){ // 通过内层for循环找出最小元素,并把最小元素所对应的索引赋值给minIndex
if (a[jx] < a[minIndex])
minIndex = jx;
}
temp = a[ix];
a[ix] = a[minIndex];
a[minIndex] = temp;
}
}
三、结果

四、选择排序时间复杂度总结:
- 平均时间复杂度:O(n**2)
- 最好情况:O(n**2)
- 最坏情况:O(n**2)
- 空间复杂度:O(1)
- 稳定性:不稳定