199 字
1 分钟
选择排序
选择排序
第一步:在数组中找到最大值,并记录最大值下标maxIndex,并将最大值与最后一个值交换,即:
swap(a[maxIndex], a[n - 1]);
第二步:在剩下的待排序数列中重新找到最大值,重复第一步 swap(a[maxIndex], a[n - 2]); 循环操作直至数列排序完成。
C++代码如下:
#include<stdio.h>#include<iostream>#include<vector>using namespace std;
void SelectSort(vector<int> &vec) {//选择排序 int maxIndex = 0; for (int i = vec.size() - 1; i >= 0; --i) { maxIndex = 0; for (int j = 0; j <= i; ++j) {//注意是j<=i,因为是找数组中最大值,包括最后一个数 if (vec[maxIndex] < vec[j]) { maxIndex = j; } } swap(vec[maxIndex], vec[i]); }}
int main() { vector<int> a = {5, 2, 3, 1, 4}; SelectSort(a); for (int i = 0; i < 5; ++i) { cout << a[i] << " "; } return 0;}