• 随机化快速排序


    #include<iostream>
    #include<cstdlib>
    #include<ctime>
    using namespace std;
    const int maxn = 5000;
    
    int main()
    {
        void Randomized_QuickSort(int A[], int p, int r);
        void out(int A[], int n);
        int n, A[maxn], B[maxn];
        cin >> n;
        for(int i  = 0; i < n; ++i)
        {
            cin >> A[i];
            B[i] = A[i];
        }
        Randomized_QuickSort(A, 0, n-1);
        out(A, n);
        return 0;
    }
    
    void Randomized_QuickSort(int A[], int p, int r)
    {
        int Randomized_Partition(int A[], int p, int r);
        if(p < r)
        {
            int q = Randomized_Partition(A, p, r);
            Randomized_QuickSort(A, p, q-1);
            Randomized_QuickSort(A, q+1, r);
        }
    }
    
    int Randomized_Partition(int A[], int p, int r)
    {
        int Partition(int A[], int p, int r);
        void exchange(int &a, int &b);
        int i = rand()%time(NULL)%(p+1)+r-p;//产生p到r的随机数
        //或者是srand(time(NULL)); rand()%(p+1)+r-p;
        //注:rand()%40产生的是0~39的随机数
        exchange(A[r], A[i]);   //交换两数,产生随机主元
        return Partition(A, p, r);
    }
    
    int Partition(int A[], int p, int r)
    {
        void exchange(int &a, int &b);
        int x = A[r];
        int i = p-1;
        for(int j = p; j < r; ++j)
        {
            if(A[j] <= x)
            {
                i = i + 1;
                exchange(A[i], A[j]);
            }
        }
        i = i + 1;
        exchange(A[i], A[r]);
        return i;
    }
    
    void exchange(int &a, int &b)
    {
        int t = a;
        a = b;
        b = t;
    }
    
    void out(int A[], int n)
    {
        for(int i  = 0; i < n; ++i)
            cout << A[i] << " ";
        cout << endl;
    }
    由于快速排序的平均性能较好,为了降低最坏情况的出现概率,提高效率,采用快速排序的随机化方案,用随机函数随即选取主元,使算法趋向于平均情况(nlgn).
  • 相关阅读:
    day70 django中间件
    day69 cookie与session
    day68 form组件
    day67 前后端数据交互
    day65 django进阶(1)
    day64 django模型层
    day63 django入门(4)
    day62 作业
    Python正课142 —— DRF 进阶3 路由与认证
    一文搞懂什么是IaaS, PaaS和SaaS
  • 原文地址:https://www.cnblogs.com/sanghai/p/2813455.html
Copyright © 2020-2023  润新知