Median of two sorted arrays of different sizes | Set 1 ( Linear ) | A utility function to find median of two integers 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
function findmedian ( a , n1 , b , n2 ) { let i = 0 ; let j = 0 ; let k ; let m1 = - 1 , m2 = - 1 ; for ( k = 0 ; k <= ( n1 + n2 ) / 2 ; k ++ ) { if ( i < n1 && 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 ; } let a = [ 1 , 12 , 15 , 26 , 38 ] ; let b = [ 2 , 13 , 24 ] ; let n1 = a . length ; let n2 = b . length ; document . write ( findmedian ( a , n1 , b , n2 ) ) ;