C++简单排序算法:
1.选择排序(不稳定,简单):
#include<bits/stdc++.h>
using namespace std;
int n, a[10005];
void sel(int pos) {
int minj = pos;
for(int i = pos + 1; i <= n; i++) {
if(a[i] <= a[minj])
minj = i;
}
if(minj != pos)
swap(a[minj], a[pos]);
for(int i = 1; i <= n; i++)
cout << a[i] << " ";
}
int main() {
cin >> n;
for(int i = 1; i <= n; i++)
cin >> a[i];
for(int i = 1; i <= n - 1; i++) {
sel(i);
cout << endl;
}
return 0;
}
2.冒泡排序(稳定,简单):
#include<bits/stdc++.h>
using namespace std;
int n, a[10005];
void bubble(int pos) {
for(int i = 1; i < pos; i++) {
if(a[i] > a[i+1])
swap(a[i], a[i+1]);
}
for(int i = 1; i <= n; i++)
cout << a[i] << " ";
}
int main() {
cin >> n;
for(int i = 1; i <= n; i++)
cin >> a[i];
for(int i = n; i >= 2; i--) {
bubble(n);
cout << endl;
}
return 0;
}
3.插入排序(稳定,较难):
#include<bits/stdc++.h>
using namespace std;
int n, a[10005];
void inr(int pos) {
int i;
//要插入的元素是pos位置的元素
int tmp = a[pos];
//通过比较找到要插入的位置
for(i = pos - 1; i >= 1; i--) {
if(a[i] > tmp) {
a[i+1] = a[i];
}
else {
break;
}
}
//要插入的位置就是第i个位置后i+1的位置
a[i+1] = tmp;
for(int i = 1; i <= n; i++)
cout << a[i] << " ";
}
int main() {
cin >> n;
for(int i = 1; i <= n; i++)
cin >> a[i];
for(int i = 2; i <= n; i++) {
inr(i);
cout << endl;
}
return 0;
}