快排三种实现

Partition 函数的三种实现方式:

/*此为算法分析与设计的版本*/
int partition(int a[],int start,int end)
{
	//int r=rand1(start,end);
		//swap(a[start],a[r]);
	int i=start,j=end+1;
	int x=a[i];
	while(1)
	{
		while(a[++i]<x&&i<end);
		while(a[--j]>x);
		if(i>=j)
			break;
		swap(a[i],a[j]);
	}
	a[start]=a[j];
	a[j]=x;
	return j;
}

下面是算法导论上的版本

/*此为算法导论上的版本*/
int partition2(int a[],int start,int end)
{
	int x=a[end];
	int i=start-1,j;
	for(j=start;j<end;j++)
	{
		if(a[j]<=x)
		{
			i++;
			swap(a[i],a[j]);
		}
	}
	swap(a[i+1],a[end]);
	return i+1;
}

严蔚敏老师的数据结构(C语言版)上的实现:

/*此为数据结构上的版本*/
int partition3(int a[],int start,int end)
{
    int key = a[start];//key初始化为a的首元素
    while(start<end)
	{ 
		while(start<end && a[end]>=key)  end--;
		a[start] = a[end];
		while(start<end && a[start]<=key)  start++;
		a[end]=a[start];
    }
    a[start]=key;
    return start;
 
}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值