随机快速排序

在快速排序中每次对数组的分界操作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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值