C++排序算法

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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值