Median of two sorted arrays of different sizes | Set 1 ( Linear ) | This function returns median of a [ ] and b [ ] . Assumptions in this function : Both a [ ] and b [ ] are sorted arrays ; Current index of i / p array a [ ] ; Current index of i / p array b [ ] ; Below is to handle the case where all elements of a [ ] are smaller than smallest ( or first ) element of b [ ] or a [ ] is empty ; Below is to handle case where all elements of b [ ] are smaller than smallest ( or first ) element of a [ ] or b [ ] is empty ; Below is to handle the case where sum of number of elements of the arrays is even ; Below is to handle the case where sum of number of elements of the arrays is odd ; Driver Code
< ? php function findmedian ( $ a , $ n1 , $ b , $ n2 ) { $ i = 0 ; $ j = 0 ; $ k ; $ m1 = -1 ; $ m2 = -1 ; for ( $ k = 0 ; $ k <= ( $ n1 + $ n2 ) / 2 ; $ k ++ ) { if ( $ i < $ n1 and $ j < $ n2 ) { if ( $ a [ $ i ] < $ b [ $ j ] ) { $ m2 = $ m1 ; $ m1 = $ a [ $ i ] ; $ i ++ ; } else { $ m2 = $ m1 ; $ m1 = $ b [ $ j ] ; $ j ++ ; } } else if ( i == n1 ) { $ m2 = $ m1 ; $ m1 = $ b [ j ] ; $ j ++ ; } else if ( $ j == $ n2 ) { $ m2 = $ m1 ; $ m1 = $ a [ $ i ] ; $ i ++ ; } } if ( ( $ n1 + $ n2 ) % 2 == 0 ) return ( $ m1 + $ m2 ) * 1.0 / 2 ; return m1 ; } $ a = array ( 1 , 12 , 15 , 26 , 38 ) ; $ b = array ( 2 , 13 , 24 ) ; $ n1 = count ( $ a ) ; $ n2 = count ( $ b ) ; echo ( findmedian ( $ a , $ n1 , $ b , $ n2 ) ) ; ? >