1 /** 2 * 排序算法之选择排序 3 **/ 4 #include <iostream> 5 #include <vector> 6 using namespace std; 7 8 void sortXuanZe(vector<int>& vec, int n) { 9 for (int i = 0; i < n - 1; ++i) { 10 int index = i; 11 for (int j = i + 1; j < n; ++j) {//寻找最小值,index代表的值为最小 12 if (vec[j] < vec[index]) { 13 index = j; 14 } 15 } 16 if (index != i) {//交换最小值与已排序的下一值 17 int temp = vec[index]; 18 vec[index] = vec[i]; 19 vec[i] = temp; 20 } 21 } 22 } 23 24 int main() { 25 vector<int> vec = {2,1,3,5,4}; 26 int len = vec.size(); 27 sortXuanZe(vec, len); 28 for (int i = 0; i < len; ++i) { 29 cout << vec[i] << endl; 30 } 31 return 0; 32 }