zoukankan      html  css  js  c++  java
  • 《算法导论》——重复元素的随机化快排Optimization For RandomizedQuickSort

      昨天讨论的随机化快排对有重复元素的数组会陷入无限循环。今天带来对其的优化,使其支持重复元素。

    只需修改partition函数即可:

    int partition(int *numArray,int head,int tail)
        {
            int pivot=numArray[tail];
            int i=head-1;
            int j=tail;
            while(true)
            {
                do
                {
                    i++;
                }while(i<=tail&&numArray[i]<pivot);    //找到比主元大的元素
                do
                {
                    j--;
                }while(numArray[j]>pivot);    //找到比主元小的元素            
                if(j<i)
                    break;
                swap(numArray,i,j);    //交换,使比主元小的元素在左边,比主元大的元素在右边
            }
            swap(numArray,j+1,tail);
            return j+1;
        }

    算法测试:

    #include "stdafx.h"
    #include <iostream>
    #include "RandomizedQuickSort.h"
    
    using namespace std;
    using namespace dksl;
    int _tmain(int argc, _TCHAR* argv[])
    {
        int a[10] = {1, 4, 8, 15, 10, 25, 54, 15, 12, 2}; 
        randomizedQuickSort(a,0,9);
        for(int i=0;i<10;i++)
            cout<<a[i]<< " ";
        cout<<endl;
        system("PAUSE");
        return 0;
    }

  • 相关阅读:
    Linux文件权限
    Linux命令
    LeetCode
    LeetCode
    LeetCode
    LeetCode
    LeetCode
    LeetCode
    LeetCode
    LeetCode
  • 原文地址:https://www.cnblogs.com/DKSL/p/3153561.html
Copyright © 2011-2022 走看看