You are interested in analyzing some hard-to-obtain data from two separate datab
ID: 3662829 • Letter: Y
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 in 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 define here to be the nth smallest value. However, the only way you can access these values is through queries to the database. 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 finds the median value using at most O(log n) queries.
Explanation / Answer
#include <bits/stdc++.h>
using namespace std;
int kthsmallest(int l[],int ll[],int m,int n,int k){
assert(m >= 0); // since we are considering l[-1] is INT_MIN so array size may be 0.
assert(n >= 0); // same as above.
assert(k > 0 && k <= m+n); // k > 0 and k <= m+n;
int i = int((float)m/(m+n)*(k-1));
int j = k-1-i;
assert(i >= 0 && i <= m);
assert(j >= 0 && j <= n);
int Ai_1,Ai,Bj_1,Bj;
if (i == 0) Ai_1 = INT_MIN;
else Ai_1 = l[i-1];
if (i == m) Ai = INT_MAX;
else Ai = l[i];
if (j == 0) Bj_1 = INT_MIN;
else Bj_1 = ll[j-1];
if (j == n) Bj = INT_MAX;
else Bj = ll[j];
if (Bj_1 < Ai && Bj > Ai) return Ai;
if (Ai_1 < Bj && Ai > Bj) return Bj;
if(Ai < Bj) return kthsmallest(l+i+1,ll,m-i-1,n,k-i-1);
if (Bj < Ai) return kthsmallest(l,ll+j+1,m,n-j-1,k-j-1);
}
int median(int A[],int B[],int m,int n){
return ((m%2 == 0 && n%2 == 0) || (m%2 == 1 && n%2 == 1)) ? (kthsmallest(A,B,m,n,(m+n)/2) + kthsmallest(A,B,m,n,((m+n)/2)+1))/2.0 : kthsmallest(A,B,m,n,(m+n+1)/2);
}
int main(){
int A[] = {1,7,9,12,32,44,61,76,92,98,102,132,144};
int B[] = {2,171,191};
cout << median(A,B,13,3) << endl;
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.