题目
略
思路
找到最小值后再交换,而不是找到一个交换一个
代码
#include<bits/stdc++.h>
using namespace std;void selectionSort(int* a, int n)
{
for (int i = 0; i < n - 1; i++){
int tmp = a[i];int tmpidx = i;for (int j = i + 1; j < n; j++){
if (a[j] < tmp){
tmp = a[j];tmpidx = j;}}int tmps = a[tmpidx];a[tmpidx] = a[i];a[i] = tmps;for (int k = 0; k < n - 1; k++){
cout << a[k] << ' ';}cout << a[n - 1] << endl;}
}int main()
{
int n; cin >> n;int* a = new int[n];for (int i = 0; i < n; i++)cin >> a[i];selectionSort(a, n);return 0;
}