cpp-algo-cases/chapter_sorting/selection_sort.cpp

35 lines
755 B
C++
Raw Normal View History

2024-02-20 16:13:23 +08:00
/**
* File: selection_sort.cpp
* Created Time: 2023-05-23
* Author: krahets (krahets@163.com)
*/
#include "../utils/common.hpp"
/* ѡ<><D1A1><EFBFBD><EFBFBD><EFBFBD><EFBFBD> */
void selectionSort(vector<int> &nums) {
int n = nums.size();
// <20><>ѭ<EFBFBD><D1AD><EFBFBD><EFBFBD>δ<EFBFBD><CEB4><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ϊ [i, n-1]
for (int i = 0; i < n - 1; i++) {
// <20><>ѭ<EFBFBD><D1AD><EFBFBD><EFBFBD><EFBFBD>ҵ<EFBFBD>δ<EFBFBD><CEB4><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ڵ<EFBFBD><DAB5><EFBFBD>СԪ<D0A1><D4AA>
int k = i;
for (int j = i + 1; j < n; j++) {
if (nums[j] < nums[k])
k = j; // <20><>¼<EFBFBD><C2BC>СԪ<D0A1>ص<EFBFBD><D8B5><EFBFBD><EFBFBD><EFBFBD>
}
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>СԪ<D0A1><D4AA><EFBFBD><EFBFBD>δ<EFBFBD><CEB4><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>׸<EFBFBD>Ԫ<EFBFBD>ؽ<EFBFBD><D8BD><EFBFBD>
swap(nums[i], nums[k]);
}
}
/* Driver Code */
int main() {
vector<int> nums = {4, 1, 3, 1, 5, 2};
selectionSort(nums);
cout << "ѡ<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ɺ<EFBFBD> nums = ";
printVector(nums);
return 0;
}