算法导论学习笔记——7快速排序

7快速排序

在这里插入图片描述
在这里插入图片描述
5

void QuickSort(ll A[],ll p,ll r)
{
	if(p<r)
	{
		ll q=Partition(A,p,r);
		QuickSort(A,p,q-1);
		QuickSort(A,q+1,r);
	}
}

在这里插入图片描述
以A[r]为分界线,将小于这个数的数全部扔到数组最前端,然后把这个数插入中间当分界线。处理完后的数组就是前i个是比A[i]小的数,后面的数都比A[i]大,A[i]是分界线。返回的是A[i]的下标i

ll Partition(ll A[],ll p,ll r)
{
	x=A[r];
	i=p-1;
	for(j=p;j<=r-1;j++)
	{
		if(A[j]<=x)
		{
			i++;
			swap(A[i],A[j]);
		}
	}
	swap(A[i+1],A[r]);
	return i+1;
}

完整程序

#include<cstdio>
#include<cstring>
#include<iostream>
#include<cmath>
#include<algorithm>
using namespace std;
typedef long long ll;
typedef pair<long long,long long> pll;
const int inf = 0x3f3f3f3f;
const int maxn=100010;
ll A[maxn];
ll Partition(ll A[],ll p,ll r)
{
	ll x=A[r];
	ll i=p-1;
	for(ll j=p;j<=r-1;j++)
	{
		if(A[j]<=x)
		{
			i++;
			swap(A[i],A[j]);
		}
	}
	swap(A[i+1],A[r]);
	return i+1;
}
void QuickSort(ll A[],ll p,ll r)
{
	if(p<r)
	{
		ll q=Partition(A,p,r);
		QuickSort(A,p,q-1);
		QuickSort(A,q+1,r);
	}
}
int main()
{
	ll n;
	scanf("%lld",&n);
	for(ll i=1;i<=n;i++)
		cin>>A[i];
	QuickSort(A,1,n);
	for(ll i=1;i<=n;i++)
		cout<<A[i]<<' ';
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值