Median of two sorted arrays of same size | This function returns median of ar1 [ ] and ar2 [ ] . Assumptions in this function : Both ar1 [ ] and ar2 [ ] are sorted arrays Both have n elements ; Since there are 2 n elements , median will be average of elements at index n - 1 and n in the array obtained after merging ar1 and ar2 ; Below is to handle case where all elements of ar1 [ ] are smaller than smallest ( or first ) element of ar2 [ ] ; Below is to handle case where all elements of ar2 [ ] are smaller than smallest ( or first ) element of ar1 [ ] ; equals sign because if two arrays have some common elements ; Store the prev median ; Store the prev median ; Driver code to test above function
def getMedian ( ar1 , ar2 , n ) : NEW_LINE INDENT i = 0 NEW_LINE j = 0 NEW_LINE m1 = - 1 NEW_LINE m2 = - 1 NEW_LINE count = 0 NEW_LINE while count < n + 1 : NEW_LINE INDENT count += 1 NEW_LINE if i == n : NEW_LINE INDENT m1 = m2 NEW_LINE m2 = ar2 [ 0 ] NEW_LINE break NEW_LINE DEDENT elif j == n : NEW_LINE INDENT m1 = m2 NEW_LINE m2 = ar1 [ 0 ] NEW_LINE break NEW_LINE DEDENT if ar1 [ i ] <= ar2 [ j ] : NEW_LINE INDENT m1 = m2 NEW_LINE m2 = ar1 [ i ] NEW_LINE i += 1 NEW_LINE DEDENT else : NEW_LINE INDENT m1 = m2 NEW_LINE m2 = ar2 [ j ] NEW_LINE j += 1 NEW_LINE DEDENT DEDENT return ( m1 + m2 ) / 2 NEW_LINE DEDENT ar1 = [ 1 , 12 , 15 , 26 , 38 ] NEW_LINE ar2 = [ 2 , 13 , 17 , 30 , 45 ] NEW_LINE n1 = len ( ar1 ) NEW_LINE n2 = len ( ar2 ) NEW_LINE if n1 == n2 : NEW_LINE INDENT print ( " Median ▁ is ▁ " , getMedian ( ar1 , ar2 , n1 ) ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Doesn ' t ▁ work ▁ for ▁ arrays ▁ of ▁ unequal ▁ size " ) NEW_LINE DEDENT