zoukankan      html  css  js  c++  java
  • 平均期望为线性时间的选择算法

    从一组无序数据中选择出第i小的元素,采用了快速排序的思想。

    #include <iostream>
    #include <algorithm>
    using namespace std;
    
    int partition(int a[], int l, int r){
        int key = a[l];
        int i=l;
        swap(a[l],a[r]);
        for(int j=l;j<r;j++)
            if(a[j]<key) swap(a[i++],a[j]);
        swap(a[i],a[r]);
        return i;
    }
    int select(int a[],int l,int r,int i)
    {
        if(l==r)
            return a[l];
        int q=partition(a,l,r);
        int k=q+1-l;
        if(k==i)
            return a[q];
        else if(k>i)
            return select(a,l,q-1,i);
        else
            return select(a,q+1,r,i-k);
    }
    int main()
    {
        int a[6] = {5,9,11,23,10,44};
        cout<<select(a,0,8,4);//获取a中第4小的元素,即11.
    }

     随机化版本

    #include <iostream>
    #include <algorithm>
    using namespace std;
    
    int rand_partition(int a[], int l, int r){
        int q=l+rand()%(r+1-l);
        int key = a[q];
        int i=l;
        swap(a[q],a[r]);
        for(int j=l;j<r;j++)
            if(a[j]<key) swap(a[i++],a[j]);
        swap(a[i],a[r]);
        return i;
    }
    int select(int a[],int l,int r,int i)
    {
        if(l==r)
            return a[l];
        int q=rand_partition(a,l,r);
        int k=q+1-l;
        if(k==i)
            return a[q];
        else if(k>i)
            return select(a,l,q-1,i);
        else
            return select(a,q+1,r,i-k);
    }
    int main()
    {
        int a[6] = {5,9,11,23,10,44};
        cout<<select(a,0,8,4);//获取a中第4大的元素,即11.
    }
  • 相关阅读:
    codeforces431C
    codeforces158C
    codeforces570C
    codeforces472C
    codeforces401C
    codeforces630C
    codeforces581C
    校内题目腐草为萤
    校内题目大美江湖
    洛谷P3370 && 字符串哈希讲解
  • 原文地址:https://www.cnblogs.com/CodeMIRACLE/p/5495378.html
Copyright © 2011-2022 走看看