顺序统计量的选择

在选择顺序统计量中,期望的时间复杂度是O(n),主要是对于给定的数组,从其中选择出第k小的值。其与原理:利用了快速排序中的随机分割区间的函数,将第k小的值分割到一个区域里面,相当于把该问题划分的时候只划分了一个子问题,就没有O(lgn),根据快速排序的时间复杂度为O(nlgn)可知,其时间复杂度为O(n)。最坏运行时间为O(n*n),遇到很坏的情况下,每次都是划分到最大的数组中。对于分割后返回的位置值,用之与k比较大小,便知道了第k小的值所在的子数组位置,一直递归,便能求出该值。代码如下:

int Insert::RandomSelect(vector<int> &coll,int begin,int end,int statistic)//statistic为第statistic小,而temp为下标,要比之小1
{
    if(begin==end)
    {
        return coll[begin];
    }
    int temp=RandomPartition(coll,begin,end);
    int temp2=temp-begin+1;
    if(temp2==statistic)
    {
        return coll[temp];
    }
    else if(statistic < temp2)
    {
       return RandomSelect(coll,begin,temp-1,statistic);
    }
    else
    {
       return RandomSelect(coll,temp+1,end,statistic-temp2);
    }
}

注意:temp2不能用temp+1代替。如果用,就会出错,因为二者在递归时begin并不相等,begin是一个变化的值,不是为0。他在statistic >temp2时begin就不为0了,十分重要。错误代码如下

int Insert::RandomSelect(vector<int> &coll,int begin,int end,int statistic)//statistic为第statistic小,而temp为下标,要比之小1
{
    if(begin==end)
    {
        return coll[begin];
    }
    int temp=RandomPartition(coll,begin,end);
    if(temp+1==statistic)//错误,会在某种情况下,循环递归,会导致栈溢出
    {
        return coll[temp];
    }
    else if(statistic < temp+1)
    {
       return RandomSelect(coll,begin,temp-1,statistic);
    }
    else
    {
       return RandomSelect(coll,temp+1,end,statistic-temp-1);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值