快排核心:枢轴 ,递归
本程序采用以数组最左值作为枢轴
#include
using namespace std;
template
void Quicksort(T *a, const int left, const int right)
{
if (left < right)
{
int i = left;
int j = right + 1;//加1(小技巧)
int pivot = a[left];//选枢轴
do{
do{
i++;
} while (a[i]<pivot);
do{
j–;
} while (a[j]>pivot);//+1使这里简便
if (i < j)
swap(a[i], a[j]);
} while (i < j);
swap(a[left], a[j]);
//递归
Quicksort(a, left, j - 1);
Quicksort(a, j + 1, right);
}
}
int main()
{
int k[] = { 3, 1, 6, 5, 2, 7, 8, 4, 9, 0, 10000 };//10000不参与排序作用与上面+1相呼应
Quicksort(k, 0, 9);
for (int i = 0; i < 11; i++)
{
cout << k[i] << endl;
}
return 0;
}
转载:https://blog.csdn.net/liudening/article/details/104525962
查看评论