其他的一些利用了分治算法的1

**小白一枚,欢迎指教

Question:

You are interested in analyzing some hard-to-obtain data from two separate databases. Each
database contains n numerical values, so there are 2n values total and you may assume that no
two values are the same. You'd like to determine the median of this set of 2n values, which we
will dene here to be the nth smallest value.
However, the only way you can access these values is through queries to the databases. In
a single query, you can specify a value k to one of the two databases, and the chosen database
will return the kth smallest value that it contains. Since queries are expensive, you would like
to compute the median using as few queries as possible.
Give an algorithm that nds the median value using at most O(log n) queries.

分析:

记两个数据库为DB1与DB2,各存储了n个数,每次从数据库中查询返回的结果值记为k1与k2。

先取DB1的最大值(k1)与DB2最小值(k2)进行判断,若k1<k2,则k1即为中位值,反之亦然。

否则,分别取DB1与DB2的第n/2小的值进行比较,若 k1与k2相等,则这个值为中位数,若k1大于k2,则继续取DB1第 n/4的值与DB2第 3n/4的值进行比较,反之亦然,依次类推,当不能再分时,相对小的那一方为两个独立数据库DB1与DB2的中间值。

伪代码:

 1 k1←n/2
 2 k2←n/2
 3 Function getMedNum(DB1,DB2,k1,k2,n)
 4         If  get(DB1,n)<get(DB2,1)  then
 5             Return  get(DB1,n)
 6 elseIf  get(DB2,n)<get(DB1,1)  then
 7             Return  get(DB2,n)
 8         End if
 9 Num1←get(DB1,k1)
10         Num2←get(DB2,k2)
11         If  min(k1,k2)<2  then
12             Return  k1<k2?k1:k2
13         End if
14         If  Num1=Num2  then
15             Return  Num1
16         elseIf  Num1>Num2 then
17             getMedNum(DB1,DB2,k1/2,(k2+n)/2)
18 elseIf  Num2>Num1 then
19             getMedNum(DB1,DB2, (k1+n)/2,k2/2)
20         End if
21 End function

 

转载于:https://www.cnblogs.com/babetterdj/p/7740091.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值