recursion - Design of an algorithm problems of Clog n[C++ code] -
two sorted arrays of integers a[1..n] , b[1..n] provided in ascending order.
q:design o(log n)-time algorithm finding out median of 2n integers. n may not power of 2.
to make thing easy, can assume o(1) algorithm return m such that:
2^m < n < 2^m+1 my problems:
nmay not power of2, mean? (understood)- i don't know how change input , make length power of 2 after found
min,maxelements both arraya,b.
you can solve in o(logn) time using binary search style approach. consider following 2 arrays:
1 1 2 2 3 1 2 3 4 5 now combined median is:
1 1 1 2 2 2 3 3 4 5 => 2 let's see how can find it. start guessing median center of each array:
1 1 2 2 3 => 2 1 2 3 4 5 => 3 logically, know combined median can't possibly less 2 or greater 3. rather, must somewhere in between these 2 values. can discard in first array smaller 2 , in second array larger 3. won't affect position of median because discarding equal number of elements on both sides of combined median is. conceptually, leaves with:
2 2 3 => 2 1 2 3 => 2 now have agreeing median, basic idea keep discarding half of entries in each of 2 arrays until have single median value.
this algorithm perform binary search, o(logn).
Comments
Post a Comment