* * Small white One, welcome advice
Question:
You is interested in analyzing some hard-to-obtain data from the separate databases. each
Database contains n numerical values, so there is 2n values total and your may assume that no
Both values are the same. Determine the median of this set of 2n values, which we
Would dene here to be the nth smallest value.
However, the only-to-do access these values are through queries to the databases. Inch
A single query, you can specify a value k to one of the databases, and the chosen database
Would return the kth smallest value that it contains. Since queries is expensive, you would like
To compute the median using as few queries as possible.
Give an algorithm that NDS the median value using the on most O (log n) queries.
Analysis:
Record two databases for DB1 and DB2, each store n number, each time from the database query returned from the result value is recorded as K1 and K2.
The maximum value of DB1 (K1) and the DB2 Minimum (K2) are evaluated first, and K1<K2 is the median value if K1, and vice versa.
Otherwise, respectively take DB1 and DB2 n/2 Small value comparison, if K1 and K2 equal, then this value is the median, if K1 is greater than K2, then continue to take DB1 the N/4 value and DB2 the value of the 3N/4 to compare, and vice versa, and so on, and so on, when no longer tick, The relatively small side is a median of two independent databases DB1 with DB2.
Pseudo code:
1k1←n/22k2←n/23 Function getmednum (db1,db2,k1,k2,n)4IfGet(Db1,n) <Get(DB2,1) Then5ReturnGet(db1,n)6ElseIfGet(Db2,n) <Get(DB1,1) Then7ReturnGet(db2,n)8Endif9num1←Get(DB1,K1)Tennum2←Get(DB2,K2) OneIf min (K1,K2) <2 Then AReturn k1<k2?K1:k2 -Endif -If num1=Num2 Then the Return Num1 -ElseIf num1>Num2 Then -Getmednum (db1,db2,k1/2, (k2+n)/2) -ElseIf num2>Num1 Then +Getmednum (DB1,DB2, (k1+n)/2, k2/2) -Endif +End function
Some of the other 1 that take advantage of the divide-and-conquer algorithm