#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); //对枢轴右边进行递归
}
}
快速排序算法(使用递归)
最新推荐文章于 2022-07-24 16:51:19 发布