【剑指offer】快速排序

概念等其他的就不说了,耳根都。。。这个其他资料都说的很清楚了,理解起来也容易,关键是自己实现下,仔细的体会。

原来看到到实现随机找个元素作为比较的哨兵元素,数组的头部一个指针,尾部一个指针,头部开始向后,找到大于哨兵的,尾部开始向前,找到小于哨兵的,然后交换。前几天看到了一个要对链表进行快排的,由于单向链表的特殊性,没法从后像前,书里的这种方法可以用在链表上,《算法导论》上好像也是这种实现。

在书中所用的方法中,我们可以从头开始,也可以从尾开始,就是把哨兵放在头部,或者是放在尾部。

#define From_Front2Back
using namespace std;

int RandomRange(int start, int end)
{
	return (start + rand()%(end - start));
}
template<class T>
int Partition(vector<T>& num, int start, int end){
	if( start >= end)
		return start;
	int index = RandomRange(start, end);
	
#ifndef From_Head2Back
	swap(num[index], num[end]);
    int large = start;
	int small = start - 1;
	while (large < end)
	{
		//take care the && order.
		if (num[large] < num[end] && ++small != large)
			swap(num[small], num[large]);
		++large;	
	}
	swap(num[++small],num[end]);
	return small;
#else
	swap(num[index], num[start]);
	int small = end;
	int large = small + 1;
	while(small > start){
		if(num[small] > num[start] && --large != small)
			swap(num[small], num[large]);
		--small;
	}
	swap(num[start], num[--large]);
	return large;
#endif
	
}

void quickSort(vector<int> &nums, int start, int end){
	if(start >= end)
		return;
	int partitionIndex = Partition(nums, start, end);
	if(partitionIndex > start)
		quickSort(nums, start, partitionIndex - 1);
	if(partitionIndex < end - 1)
		quickSort(nums, partitionIndex + 1, end);
}
void main(){
    const int numLength = 10;
	const int range = 50;
	vector<int> nums;
	for (int i = 0; i < numLength; ++i)
		nums.push_back(rand()%range);
	quickSort(nums, 0, numLength - 1);
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值