赞
踩
以下是C++实现的选择排序代码:
#include <iostream> #include <vector> using namespace std; void selectionSort(vector<int>& arr) { int n = arr.size(); for (int i = 0; i < n - 1; i++) { int minIndex = i; for (int j = i + 1; j < n; j++) { if (arr[j] < arr[minIndex]) { minIndex = j; } } if (minIndex != i) { swap(arr[i], arr[minIndex]); } } } int main() { vector<int> arr = {5, 3, 8, 6, 2, 7, 1, 4}; selectionSort(arr); for (int i = 0; i < arr.size(); i++) { cout << arr[i] << " "; } cout << endl; return 0; }
C:\Users\Administrator\CLionProjects\untitled1\cmake-build-debug\untitled1.exe
1 2 3 4 5 6 7 8
Process finished with exit code 0
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。