您的位置:首页 > 其它

快排 随机分割

2016-04-28 00:14 302 查看
计算机算法设计与分析第四版[王]

#include<iostream>
#include <stdlib.h>
using namespace std;
inline void swap(int &a, int &b)
{
int c = a;
a = b;
b = c;
}
//随机分割
int Random(int a, int b)//随机在a--b选择一个整数
{
return a + rand() % (b - a + 1);
}
template<class type>
int RandomizedPartition(type a[], int p, int r)//随机分割
{
int i = Random(p, r);//在p--r中随机选择一个数
swap(a[i], a[p]);
return Partition(a, p, r);
}
template<class type>
int Partition(type a[], int p, int r)//以随机选的那个数作为分割起点,p此时是之前随机选的a[i]的位置;
{
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 RandomizedQuickSort(type a[], int p, int r)
{
if (p < r)
{
int q = RandomizedPartition(a, p, r);
RandomizedQuickSort(a, p, q - 1);//左半端排序
RandomizedQuickSort(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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  快速排序