带权中位数-算法导论第三版第九章思考题9-2
b
时间复杂度O(nlgn)
float find_median_with_weights_b(float *array,int length)
{
quick_sort<float>(array,0,length-1);
float sum = 0;
int index = 0;
while (sum < 0.5)
{
sum += array[index];
index++;
}
return array[index-1];
}
辅助代码quick_sort
链接地址
c
时间复杂度Θ(n)
float find_median_with_weights_c(float *array,int start,int end,float last_left_sum,float last_right_sum)
{
select<float>(array,start,end,(end - start)/2);
float left_sum = 0;
float right_sum = 0;
for (int i = start; i < start + (end - start)/2; ++i) {
left_sum += array[i];
}
for (int i = start + (end - start)/2 + 1 ;i < end+1; ++i) {
right_sum+=array[i];
}
if(left_sum+last_left_sum < 0.5 && right_sum +last_right_sum< 0.5)
{
return array[start + (end - start)/2];
}
else if(left_sum>0.5)
{
last_right_sum += right_sum;
end = (end - start)/2 - 1;
}
else
{
last_left_sum += left_sum;
start = start + (end - start)/2;
}
return find_median_with_weights_c(array,start,end,last_left_sum,last_right_sum);
}
float find_median_with_weights_c(float *array,int length)
{
return find_median_with_weights_c(array,0,length-1,0,0);
}
辅助代码select
链接地址