c++快速排序(三平均划分法优化)

题目背景:要求编写函数qsort来实现快速排序,用户依次输入待排序数据个数、待排序数据以及排序方式。

注意:要求平均时间复杂度为O(n logn)

样例输入:

5

88 25 63 10 7

0

样例输出:

7 10 25 63 88

示例代码:

#include<iostream>
using namespace std;

void swap(int& a, int& b)
{
	int tmp = a;
	a = b;
	b = tmp;
}
void cmpswap(int& a, int& b)
{
	if (a < b)
	{
		swap(a, b);
	}
}
void qsort(int a[], int s, int e, int f)
{
	if (s >= e) return;	//递归结束的基线条件
	//三平均划分法使基准值随机,优化时间复杂度
	int m = s + (e - s) / 2;	
	cmpswap(a[m], a[s]);
	cmpswap(a[s], a[e]);
	int pivot = a[s];	//选待排序数组第一个元素为基准值
	//左右哨兵指针
	int i = s + 1;
	int j = e;
	while (1)
	{
		if (f == 0)	//从小到大排序
		{
			while (a[j] > pivot) j--;	//基准值为第一个元素,必须右哨兵先移动
			while (a[i] < pivot && i < e) i++;
		}
		else        //从大到小排序
		{
			while (a[j] < pivot) j--;
			while (a[i] > pivot && i < e) i++;
		}

		if (i < j)
		{
			swap(a[i], a[j]);
			i++;
			j--;
		}
		//基线条件,当左右哨兵碰头或越界时
		else
		{
			swap(a[s], a[j]);
			break;
		}
	}
	//递归,对基准值左右两部分子数组递归地快排
	qsort(a, s, j - 1, f);
	qsort(a, j + 1, e, f);
}

int main()
{
	cout << "The amount of numbers is:\n";
	int n;
	cin >> n;
	int a[100];
	cout << "Input numbers:\n";
	for (int i = 0; i < n; i++)
	{
		cin >> a[i];
	}
	int flag = 0;
	cout << "Choose the way of sorting: 0->small to large, 1->large to small :\n";
	cin >> flag;
	qsort(a, 0, n - 1, flag);
	for (int i = 0; i < n; i++)
	{
		if (i < n - 1)
			cout << a[i] << " ";
		else
			cout << a[i] << endl;
	}
	return 0;
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值