Introduction to algorithms: Median of two sorted
Problem Source
Introduction to algorithms p223 9.3-8:
Let X [1 .. n] and y [1 .. n] Be two arrays, each containing nnumbers already in sorted order. give an O (lgn)-time algorithm to find themedian of all 2n elements in arrays X and Y.
Returns the median of two sorted arrays A and B with equal length (n elements ).
Solution 1: merge the two arrays until the n elements (complexity O (N) are counted. solution 2: Starting from the median of, binary Search until the condition is met (complexity O (lgn ))
Refer to: https://gist.github.com/richzw/3780428. Note: There are obvious errors in the reference code.
This is also the requirement in the question. Starting from the median of A, that is, k = (n-1)/2, if the pointer of B is n-1-k, it can ensure that the number of elements in a smaller than a [k] isK, B is less than B [n-1-k]-the element isN-1-k (s), As long as the second part finds a [k] that meets the following conditions, the number of elements a and B smaller than a [k] is n-1, A [k] is the nth number, that is, the median.
A [k]> = B [n-k-1] & A [k] <= B [n-k]
/*** Creation Time: 10:25:49, January 1, August 18, 2014 * Project name: test * @ author caoyanfeng * @ sincejdk 1.6.0 _ 21 * class description: compiled by */Public classmedianoftowarray {/*** @ paramargs */public static voidmain (string [] ARGs) {// todoauto-generated method stub int [] array1 = {4, 5, 6, 7}; int [] array2 = {3, 5, 6, 7};/* returns the center value of {3, 4, 5, 6, 7, that is, 6 or 5 */INT result1 = medianoftowarray2 (array1, array2); int result2 = getmedian (array1, 0, array1.length-1, array1.length, array2); system. out. println ("perform the initial determination before recursion:" + result1 + "\ n direct recursion:" + result2 );} /* exclude two special cases (where a and B do not overlap) and perform recursive Binary Search */public static int medianoftowarray2 (INT [] array1, int [] array2) {int n = array1.length; If (array1 [n-1] <array2 [0]) {return array1 [n-1];} else if (array2 [n-1] <array1 [0]) {return array2 [n-1];} else {return getmedian (array1, 0, n-1, N, array2) ;}/ * perform Binary Search recursively. See the error code, */public static intgetmedian (INT [] array1, int low, int high, int N, int [] array2) {int K = (high + low)/2; if (k = n-1 | K = 0) {return array1 [k];} else if (k> 0 & K <n-1 & array1 [k]> = array2 [n-k-1] & array1 [k] <= array2 [n-k]) {return array1 [k];} else if (array1 [k]> array2 [n-k-1]) {return getmedian (array1, low, K-1, N, array2 );} else {return getmedian (array1, k + 1, high, N, array2 );}}}