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
def findmedian ( a , n1 , b , n2 ) : NEW_LINE INDENT j = 0 NEW_LINE m1 = - 1 NEW_LINE m2 = - 1 NEW_LINE for k in range ( ( ( n1 + n2 ) // 2 ) + 1 ) : NEW_LINE INDENT if ( i < n1 and j < n2 ) : NEW_LINE INDENT if ( a [ i ] < b [ j ] ) : NEW_LINE INDENT m2 = m1 NEW_LINE m1 = a [ i ] NEW_LINE i += 1 NEW_LINE DEDENT else : NEW_LINE INDENT m2 = m1 NEW_LINE m1 = b [ j ] NEW_LINE j += 1 NEW_LINE DEDENT DEDENT elif ( i == n1 ) : NEW_LINE INDENT m2 = m1 NEW_LINE m1 = b [ j ] NEW_LINE j += 1 NEW_LINE DEDENT elif ( j == n2 ) : NEW_LINE INDENT m2 = m1 NEW_LINE m1 = a [ i ] NEW_LINE i += 1 NEW_LINE DEDENT DEDENT if ( ( n1 + n2 ) % 2 == 0 ) : NEW_LINE INDENT return ( m1 + m2 ) * 1.0 / 2 NEW_LINE DEDENT return m1 NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ 1 , 12 , 15 , 26 , 38 ] NEW_LINE b = [ 2 , 13 , 24 ] NEW_LINE n1 = len ( a ) NEW_LINE n2 = len ( b ) NEW_LINE print ( findmedian ( a , n1 , b , n2 ) ) NEW_LINE DEDENT