快速排序算法的C++实现

时间复杂度平均情况接近O(nlgn)

template<class T>
void swap(T data[], int a, int b){
	T temp = data[a];
	data[a] = data[b];
	data[b] = temp;
}
void quicksort(T data[], int first, int last){
	int lower = first+1, upper = last;//双指针
	
	//选择中间的数字放在第一个作为bound
	swap(data,first,(first+last)/2);
	T bound = data[first];
	//双指针移动直到upper在前
	while(lower<=upper){
	
		//左指针右移直到指向大于bound的位置
		while(data[lower] <= bound)
			lower++;
		//右指针左移直到指向小于bound的位置
		while(data[upper] >= bound)
			upper--;
		//完成上述移动后,要么左指针在左,需要继续交换移动;要么左指针在右,可以跳出循环开始左右子序列的递归
		if(lower<upper){
			swap(data,lower,upper);
		}
	}

	//upper指向小于bound的位置,因此交换first和bound作为左右序列的分割
	swap(data,first,upper);
	if(first<upper-1)
		quicksort(data, first,upper-1);
	if(upper+1<last)
		quicksort(data,upper+1,last);
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值