五种新手常用的排序算法

排序算法

1.桶排序

桶排序,时间复杂度O(n),在数据比较小的范围内运行速度速度比较快,比快排更好,但是它的弊端也很明显,对于像(1,2,999999999999999) 这样的排序,会占用很多的时间和空间。也就是说,当数据值域很大且分布不均匀时,效率会很低。

#include<iostream>
using namespace std;

const int N = 100010;
int q[N];

int main()
{
	int n, x;
	cin >> n;
	while (n--)
	{
		cin >> x;
		q[x]++;
	}
	for (int i = 0; i < N; i++)
		while (q[i]--)
			cout << i << " ";
	cout << endl;
}

2.冒泡排序
时间复杂度O(n2)。

#include<stdio.h>
#define N 1000
int t, i, j, m, a[N];
int main(){
	int n;
	scanf_s("%d", &n);
	for(i=0;i<n;i++)
		scanf("%d",&a[i]);
	for(i=1;i<n;i++){
		for(t=0;t<n-1;t++){
			if(a[t]>a[t+1]){
				m=a[t];
				a[t]=a[t+1];
				a[t+1]=m;
			}
		}
	}
	for(i=0;i<n;i++)
		printf("%d ",a[i]);
	printf("\n");
} 

3.快速排序
快速排序,平均时间复杂度O(nlogn), 不稳定。

#include<iostream>
using namespace std;

const int N = 1000010;
int q[N];
void quick_sort(int l, int r)
{
	if (l >= r) return;
	int x = q[(l + r) >> 1], i = l - 1, j = r + 1;
	while (i < j)
	{
		do i++; while (q[i] < x);
		do j--; while (q[j] > x);
		if (i < j)
		{
			int temp = q[i];
			q[i] = q[j];
			q[j] = temp;
		}
	}
	quick_sort(l, j);
	quick_sort(j + 1, r);
}

int main()
{
	int m;
	cin >> m;
	for (int i = 0; i < m; i++) cin >> q[i];
	quick_sort(0, m - 1);
	for (int i = 0; i < m; i++) cout << q[i] << " ";
	cout << endl;
}

4.归并排序
归并排序,稳定的O(nlogn)。

#include<iostream>
using namespace std;

const int N = 100010;
int a[N], b[N];

void merge_sort(int l, int r)
{
	int k = 0;
	if (l == r) return;
	int m = (l + r) >> 1;
	merge_sort(l, m); merge_sort(m + 1, r);
	int i = l, j = m + 1;
	while (i <= m && j <= r)
	{
		if (a[i] < a[j])
			b[k++] = a[i++];
		else
			b[k++] = a[j++];
	}
	while (i <= m) b[k++] = a[i++];
	while (j <= r) b[k++] = a[j++];
	for (int i = l, j = 0; i <= r; i++, j++)
		a[i] = b[j];
	return;
}

int main()
{
	int n;
	cin >> n;
	for (int i = 0; i < n; i++) cin >> a[i];
	merge_sort(0, n - 1);
	for (int i = 0; i < n; i++) cout << a[i] << " ";
	cout << endl;
}

5.堆排序

#include<iostream>
#include<algorithm>
using namespace std;

const int N = 100010;

int h[N], cnt, n, m;

void down(int u)
{
	int t = u;
	if (u * 2 <= cnt && h[u * 2] < h[t]) t = u * 2;
	if (u * 2 + 1 <= cnt && h[u * 2 + 1] < h[t]) t = u * 2 + 1;
	if (t != u)
	{
		swap(h[t], h[u]);
		down(t);
	}
}

int main()
{
	cin >> n;
	for (int i = 1; i <= n; i++) cin >> h[i];
	for (int i = n / 2; i; i--) down(i);
	cnt = n;
	while (n--)
	{
		cout << h[1] << " ";
		h[1] = h[cnt--];
		down(1);
	}
	cout << endl;
	return 0;
}
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值