计算机算法设计与分析第四版[王]
#include<iostream>
#include <stdlib.h>
using namespace std;
inline void swap(int &a, int &b)
{
int c = a;
a = b;
b = c;
}
//一般分割
template<class type>
int Partition(type a[], int p, int r)//以第一个位置作为分割起点
{
int i = p, j = r + 1;
type x = a[p];
while (true)
{
while (a[++i] < x&&i < r);
while (a[--j] > x);
if (i >= j) break;
swap(a[i], a[j]);
}
a[p] = a[j];
a[j] = x;
return j;//返回结束后分割点所在的位置
}
template<class type>
void QuickSort(type a[], int p, int r)
{
if (p < r)
{
int q = Partition(a, p, r);
QuickSort(a, p, q - 1);//对右边排序
QuickSort(a, q + 1, r);//对左边排序
}
}
int main()
{
int a[] = { 5,1,66,44,87,32,12,66,99,45,32,156,456 };
RandomizedQuickSort(a, 0, 12);
for (int i = 0;i < 12;i++)
{
cout << a[i] << endl;
}
}