(九)快速排序随机化版本

快速排序随机化版本

1、描述

       采用一种称为随机抽样(random sampling)的随机化技术,使得分析更加简单。与始终采用A[r]作为主元的方法不同,随机抽样是从子数组A[p…r]中随机选择一个元素作为主元。首先将A[r]与从A[p…r]中随机选出的一个元素交换。通过对序列p,…,r的随机抽样,可以保证主元元素x=A[r]是等概率地从子数组的r-p+1个元素中选取的。
PARTITION(A,p,r)
1	x=A[r]
2	i=p-1
3	for j=p to r-1
4	  if A[j]≤x
5	    i=i+1
6	    Exchange A[i] with A[j]
7	Exchange A[i+1] with A[r]
8	Return i+1
RANDOMIZED-PARTITION(A,p,r)
1	i=RADOM(p,r)
2	exchange A[r] with A[i]
3	return PARTITION(A,p,r)
RANDOMIZED-QUICKSORT(A,p,r)
1	if p<r
2	  q= RANDOMIZED-PARTITION(A,p,r)
3	  RANDOMIZED-QUICKSORT(A,p,q-1)
4	  RANDOMIZED-QUICKSORT(A,q+1,r)

2、具体实现

/*快速排序随机化版本*/
#include <iostream>
#include <time.h>
using namespace std;

//打印数组
void PrintRandomizedQuickSort(int *arr, int len)
{
	for (int i = 0; i < len; i++)
	{
		cout << arr[i] << " ";
	}
	cout << endl;
}

//交换
void Swap(int *a, int *b)
{
	int temp;
	temp = *a;
	*a = *b;
	*b = temp;
}

//划分
int Partition(int *arr, int p, int r)
{
	int i, x;
	x = arr[r];
	i = p - 1;
	for (int j = p; j < r; j++)
	{
		if (arr[j] <= x)
		{
			i++;
			Swap(&arr[i], &arr[j]);
		}
	}
	Swap(&arr[i + 1], &arr[r]);
	return i+1;
}

//随机分治思想划分
int RandomizedPartition(int *arr, int p, int r)
{
	int i;
	srand((unsigned)time(NULL));
	i = rand() % (r - p + 1) + p;
	Swap(&arr[r], &arr[i]);
	return Partition(arr, p, r);
}

//快速排序随机化版本
void RandomizedQuickSort(int *arr, int p, int r)
{
	int q;
	if (p < r)
	{
		q = RandomizedPartition(arr, p, r);
		RandomizedQuickSort(arr, p, q - 1);
		RandomizedQuickSort(arr, q + 1, r);
	}
}
int main()
{
	int len = 0;
	int array[] = { 3, 2, 9, 0, 7, 5, 4, 8, 6, 1 };

	//数组长度
	len = sizeof(array) / sizeof(int);
	//快排前的顺序
	cout << "Before Randomized Quick Sort array:" << endl;
	PrintRandomizedQuickSort(array, len);
	//快速排序随机化版本
	RandomizedQuickSort(array, 0, len - 1);
	//快排后的顺序
	cout << "After Randomized Quick Sort array:" << endl;
	PrintRandomizedQuickSort(array, len);

	system("pause");
	return 0;
}



猜你喜欢

转载自blog.csdn.net/ailunlee/article/details/80269805