【算法】快速排序

快速排序是一种采用分治思想解决问题的算法。
#include<iostream>
using namespace std;
void Swap(int &a,int &b)
{
	int temp;
	temp = a;
	a = b;
	b = temp;
}

void QucikSort(int c[],int left,int right)
{
	if(left >= right)
		return;
	int l,r;
	int compete;
	compete = c[left];//比较数,基准 
	l = left;
	r = right;
	while(l != r)
	{
		//顺序一定要从右边开始,这样循环结束 l 所在位置 c[l] < c[left] <c[l+1] 
		while(c[r] >= compete&&l < r)//从右开始比基准小的数 
			r--;
		while(c[l] <= compete&&l < r)//从左开始比基准大的数
			l++;
		if(l < r)
		{
			Swap(c[l],c[r]); //交换 
		}
	}
	Swap(c[l],c[left]);  //把基准换到数大小的中间 
	QucikSort(c,left,l-1);//分治 
	QucikSort(c,l+1,right);
}

int main()
{
	int c[1001],n;
	cout << "请输入排序的位数:"; 
	cin >> n;
	for(int i = 0;i<n;i++)  //输入 
		cin >> c[i];
	QucikSort(c,0,n-1);
	for(int i = 0;i<n;i++)  //显示 
		cout << c[i] <<" ";
	cin.get();
	return 0;
}

运行如下:


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值