线性时间选择算法

直接上代码

理论部分后续再加

#include<iostream>
using namespace std;

void Swap(int &a, int &b)
{
    int tmp;
    tmp = a;
    a = b;
    b = tmp;
}

int Partition(int a[], int p, int r)
{
    int i = p-1;
    int pivot = a[r];
    for (int j=p;j<r;j++)
    {
        if (a[j]<=pivot)
        {
            i++;
            Swap(a[i],a[j]);
        }
    }
    Swap(a[i+1],a[r]);
    return i+1;
}

void SelectSort(int a[], int p, int r)
{
    for (int i=p;i<r;i++)
    {
        for (int j=i+1;j<=r;j++)
        {
            if (a[i]>a[j])
            Swap(a[i],a[j]);
        }
    }
}

int Select(int a[], int p, int r, int k)
{
    if (r-p<7)
    {
        SelectSort(a,p,r);
        return a[p+k-1];
    }

    for (int i=0;i<(r-p)/5;i++)
    {
        int j = p+5*i;
        SelectSort(a,j,j+4);
        Swap(a[p+i],a[j+2]);
    }
    int x = Select(a,p,p+(r-p)/5-1,(r-p)/10);
    int index_x = p+(r-p)/10;
    Swap(a[index_x],a[r]);
    int key1,key2; 
    key1 = Partition(a,p,r);
    key2 = key1-p+1; 
    if (k<key2)
    {
        return Select(a,p,key1-1,k);
    }
    if (k>key2) 
    {
        return Select(a,key1+1,r,k-key2);
    }
    return a[key1];
}



int main()
{
    int n=35;
    int a[]={17,18,19,20,21,22,23,24,25,26,27,28,29,30,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,41,46,59,90,87};
//  int x = Partition(a,0,30);
//  cout<<x<<endl;
    cout<<endl;
    cout<<"初始关键字 ";     
    for (int i=0;i<n;i++)
        cout<<a[i]<<" ";
    cout<<endl;
    for (int k=1;k<=n;k++)
    {
    int temp;
    temp=Select(a,0,n-1,k);
    cout<<"第"<<k<<"小的元素是"<<temp<<endl;
    cout<<endl;
    } 
    return 0;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值