快速排序算法(使用递归)

#include<iostream>

using namespace std;

template<class T>

void quickSort(T *p, const int left, const int right);

int main()
{
	int a[] = { 2,1,5,6,8,4,9,7,0,3,99 };
	quickSort(a, 0, 9);
	for (int i = 0; i < 10; i++)
	{
		cout << a[i] << endl;
	}
	cin.get();

	return 0;
}


template<class T>
void quickSort(T *p, const int left, const int right)
{
	if (left < right) {
		int i = left;
		int j = right + 1; //+1是为了简化第32行代码
		int pivot = p[left]; //取最左边为枢轴
		do {
			do i++; while (p[i] < pivot);
			do j--; while (p[j] > pivot);
			if (i < j) swap(p[i], p[j]);

		} while (i < j);

		swap(p[left], p[j]); //将枢轴交换到j的位置,因为j位置的值比枢轴小
		quickSort(p, left, j - 1); //对枢轴左边yo进行递归
		quickSort(p, j + 1, right); //对枢轴右边进行递归
	}
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值