您的位置:首页 > 其它

顺序统计量的选择

2015-12-10 10:40 183 查看
在选择顺序统计量中,期望的时间复杂度是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);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: