Median of two sorted arrays of different sizes | Set 1 ( Linear ) | A C ++ program to find median of two sorted arrays of unequal sizes ; 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 program to test above functions
#include <bits/stdc++.h> NEW_LINE using namespace std ; float findmedian ( int a [ ] , int n1 , int b [ ] , int n2 ) { int i = 0 ; int j = 0 ; int k ; int 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 ; } int main ( ) { int a [ ] = { 1 , 12 , 15 , 26 , 38 } ; int b [ ] = { 2 , 13 , 24 } ; int n1 = sizeof ( a ) / sizeof ( a [ 0 ] ) ; int n2 = sizeof ( b ) / sizeof ( b [ 0 ] ) ; printf ( " % f " , findmedian ( a , n1 , b , n2 ) ) ; return 0 ; }