#include <bits/stdc++.h> using namespace std;
void selectionSort(int a[], int n) { for (int i = 1; i < n; i++) { int mn = 1e9, idx = 0; for (int j = i; j <= n; j++) { if (mn > a[j]) { mn = a[j], idx = j; } swap(a[i], a[idx]); } } }
int main() { int a[1005], n; cin >> n; for (int i = 1; i <= n; i++) cin >> a[i]; selectionSort(a, n); for (int i = 1; i <= n; i++) cout << a[i] << " "; return 0; }
共 1 条回复
swap(a[i], a[idx]);
放到j循环的外面,j循环找最小值,循环结束了才能确定最小值的位置。