在快速排序中每次对数组的分界操作Partition都是以数组的末位点作为分界点(key),这样就带来了一个问题——当待排序数组是一个已排好序的数组时,快速排序的执行时间是O(n平方),在执行 时间上比较耗时,于是就有了随机快速排序的思想。
在随机快速排序中,每次对数组的分界操作Partition都是在数组中随机寻找一个元素作为分界点(key),这样就避免了上诉问题,随机排序的平均在执行时间为O(n*lg(n))。比上面的O(n平方)有很大的提高。
代码详解:
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <time.h>
void PrintArr(int *pnArr, int nLen)
{
for (int i = 0; i < nLen; i++)
{
printf("%d ", pnArr[i]);
}
printf("\n");
}
void Swap(int *p1, int *p2)
{
int nTmp = *p1;
*p1 = *p2;
*p2 = nTmp;
}
int Partition(int *pnArr, int nLeft, int nRight)
{
int nKey = nRight;
int i = nLeft - 1;
for (int j = nLeft; j < nRight; j++)
{
if (pnArr[j] < pnArr[nKey])
{
i++;
Swap(&pnArr[i], &pnArr[j]);
}
}
Swap(&pnArr[i+1], &pnArr[nRight]);
return i + 1;
}
int RandomPartition(int *pnArr, int nLeft, int nRight)
{
srand(time(NULL));
int nKey = rand()%(nRight - nLeft + 1) + nLeft;
Swap(&pnArr[nKey], &pnArr[nRight]);
return Partition(pnArr, nLeft, nRight);
} //随机选择一个地址,小组最后一个数跟这个地址的值交换,进行排序
void QuickSort(int *pnArr, int nLeft, int nRight)
{
if (nLeft < nRight)
{
int nTmpPos = RandomPartition(pnArr, nLeft, nRight);
QuickSort(pnArr, nLeft, nTmpPos - 1);
QuickSort(pnArr, nTmpPos + 1, nRight);// 跟归并算法类似, 将数组分为左右两个部分,分别进行排序
}
}
int main()
{
int nArr[10] = {42,1,3,2,16,9,10,14,8,17};
PrintArr(nArr, 10);
QuickSort(nArr, 0,9);
PrintArr(nArr, 10);
system("pause");
return 0;
}