Open In App

Median of two sorted arrays of same size

Last Updated : 09 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report
 

There are 2 sorted arrays A and B of size n each. Write an algorithm to find the median of the array obtained after merging the above 2 arrays(i.e. array of length 2n). The complexity should be O(log(n))

median-of-two-arrays

Note: Since the size of the set for which we are looking for the median is even (2n), we need to take the average of the middle two numbers and return the floor of the average.

Method 1 (Simply count while Merging) 

Use the merge procedure of merge sort. Keep track of count while comparing elements of two arrays. If count becomes n(For 2n elements), we have reached the median. Take the average of the elements at indexes n-1 and n in the merged array. See the below implementation. 

C




// A Simple Merge based O(n) solution to find median of
// two sorted arrays
#include <stdio.h>
 
/* This function returns median of ar1[] and ar2[].
   Assumptions in this function:
   Both ar1[] and ar2[] are sorted arrays
   Both have n elements */
int getMedian(int ar1[], int ar2[], int n)
{
    int i = 0;  /* Current index of i/p array ar1[] */
    int j = 0; /* Current index of i/p array ar2[] */
    int count;
    int m1 = -1, m2 = -1;
 
    /* Since there are 2n elements, median will be average
     of elements at index n-1 and n in the array obtained after
     merging ar1 and ar2 */
    for (count = 0; count <= n; count++)
    {
        /*Below is to handle case where all elements of ar1[] are
          smaller than smallest(or first) element of ar2[]*/
        if (i == n)
        {
            m1 = m2;
            m2 = ar2[0];
            break;
        }
 
        /*Below is to handle case where all elements of ar2[] are
          smaller than smallest(or first) element of ar1[]*/
        else if (j == n)
        {
            m1 = m2;
            m2 = ar1[0];
            break;
        }
         /* equals sign because if two
            arrays have some common elements */
        if (ar1[i] <= ar2[j])
        {
            m1 = m2;  /* Store the prev median */
            m2 = ar1[i];
            i++;
        }
        else
        {
            m1 = m2;  /* Store the prev median */
            m2 = ar2[j];
            j++;
        }
    }
 
    return (m1 + m2)/2;
}
 
/* Driver program to test above function */
int main()
{
    int ar1[] = {1, 12, 15, 26, 38};
    int ar2[] = {2, 13, 17, 30, 45};
 
    int n1 = sizeof(ar1)/sizeof(ar1[0]);
    int n2 = sizeof(ar2)/sizeof(ar2[0]);
    if (n1 == n2)
        printf("Median is %d", getMedian(ar1, ar2, n1));
    else
        printf("Doesn't work for arrays of unequal size");
    getchar();
    return 0;
}


C++




// A Simple Merge based O(n)
// solution to find median of
// two sorted arrays
#include <bits/stdc++.h>
using namespace std;
 
/* This function returns
median of ar1[] and ar2[].
Assumptions in this function:
Both ar1[] and ar2[]
are sorted arrays
Both have n elements */
double getMedian(int ar1[], int ar2[], int n)
{
    int i = 0; /* Current index of
                  i/p array ar1[] */
    int j = 0; /* Current index of
                  i/p array ar2[] */
    int count;
    int m1 = -1, m2 = -1;
 
    /* Since there are 2n elements,
    median will be average of elements
    at index n-1 and n in the array
    obtained after merging ar1 and ar2 */
    for (count = 0; count <= n; count++) {
        /* Below is to handle case where
           all elements of ar1[] are
           smaller than smallest(or first)
           element of ar2[]*/
        if (i == n) {
            m1 = m2;
            m2 = ar2[0];
            break;
        }
 
        /*Below is to handle case where
          all elements of ar2[] are
          smaller than smallest(or first)
          element of ar1[]*/
        else if (j == n) {
            m1 = m2;
            m2 = ar1[0];
            break;
        }
        /* equals sign because if two
           arrays have some common elements */
        if (ar1[i] <= ar2[j]) {
            /* Store the prev median */
            m1 = m2;
            m2 = ar1[i];
            i++;
        }
        else {
            /* Store the prev median */
            m1 = m2;
            m2 = ar2[j];
            j++;
        }
    }
 
    return (1.0 * (m1 + m2)) / 2;
}
 
// Driver Code
int main()
{
    int ar1[] = {1, 12, 15, 26, 38};
    int ar2[] = {2, 13, 17, 30, 45};
 
    int n1 = sizeof(ar1) / sizeof(ar1[0]);
    int n2 = sizeof(ar2) / sizeof(ar2[0]);
    if (n1 == n2)
        cout << "Median is " << getMedian(ar1, ar2, n1);
    else
        cout << "Doesn't work for arrays"
             << " of unequal size";
    getchar();
    return 0;
}
 
// This code is contributed
// by Shivi_Aggarwal


Java




// A Simple Merge based O(n) solution
// to find median of two sorted arrays
 
class Main
{
    // function to calculate median
    static int getMedian(int ar1[], int ar2[], int n)
    {  
        int i = 0
        int j = 0;
        int count;
        int m1 = -1, m2 = -1;
      
        /* Since there are 2n elements, median will
           be average of elements at index n-1 and
           n in the array obtained after merging ar1
           and ar2 */
        for (count = 0; count <= n; count++)
        {
            /* Below is to handle case where all
              elements of ar1[] are smaller than
              smallest(or first) element of ar2[] */
            if (i == n)
            {
                m1 = m2;
                m2 = ar2[0];
                break;
            }
      
            /* Below is to handle case where all
               elements of ar2[] are smaller than
               smallest(or first) element of ar1[] */
            else if (j == n)
            {
                m1 = m2;
                m2 = ar1[0];
                break;
            }
            /* equals sign because if two
               arrays have some common elements */
            if (ar1[i] <= ar2[j])
            {  
                /* Store the prev median */
                m1 = m2; 
                m2 = ar1[i];
                i++;
            }
            else
            {
                /* Store the prev median */
                m1 = m2; 
                m2 = ar2[j];
                j++;
            }
        }
      
        return (m1 + m2)/2;
    }
      
    /* Driver program to test above function */
    public static void main (String[] args)
    {
        int ar1[] = {1, 12, 15, 26, 38};
        int ar2[] = {2, 13, 17, 30, 45};
      
        int n1 = ar1.length;
        int n2 = ar2.length;
        if (n1 == n2)
            System.out.println("Median is " +
                        getMedian(ar1, ar2, n1));
        else
            System.out.println("arrays are of unequal size");
    }   
}


Python3




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


C#




// A Simple Merge based O(n) solution
// to find median of two sorted arrays
using System;
class GFG
{
    // function to calculate median
    static int getMedian(int []ar1,
                         int []ar2,
                         int n)
    {
        int i = 0;
        int j = 0;
        int count;
        int m1 = -1, m2 = -1;
     
        // Since there are 2n elements,
        // median will be average of
        // elements at index n-1 and n in
        // the array obtained after
        // merging ar1 and ar2
        for (count = 0; count <= n; count++)
        {
            // Below is to handle case
            // where all elements of ar1[] 
            // are smaller than smallest
            // (or first) element of ar2[]
            if (i == n)
            {
                m1 = m2;
                m2 = ar2[0];
                break;
            }
     
            /* Below is to handle case where all
            elements of ar2[] are smaller than
            smallest(or first) element of ar1[] */
            else if (j == n)
            {
                m1 = m2;
                m2 = ar1[0];
                break;
            }
            /* equals sign because if two
            arrays have some common elements */
            if (ar1[i] <= ar2[j])
            {
                // Store the prev median
                m1 = m2;
                m2 = ar1[i];
                i++;
            }
            else
            {
                // Store the prev median
                m1 = m2;
                m2 = ar2[j];
                j++;
            }
        }
     
        return (m1 + m2)/2;
    }
     
    // Driver Code
    public static void Main ()
    {
        int []ar1 = {1, 12, 15, 26, 38};
        int []ar2 = {2, 13, 17, 30, 45};
     
        int n1 = ar1.Length;
        int n2 = ar2.Length;
        if (n1 == n2)
            Console.Write("Median is " +
                        getMedian(ar1, ar2, n1));
        else
            Console.Write("arrays are of unequal size");
    }
}


PHP




<?php
// A Simple Merge based O(n) solution
// to find median of two sorted arrays
 
// This function returns median of
// ar1[] and ar2[]. Assumptions in
// this function: Both ar1[] and ar2[]
// are sorted arrays Both have n elements
function getMedian($ar1, $ar2, $n)
{
    // Current index of i/p array ar1[]
    $i = 0;
     
    // Current index of i/p array ar2[]
    $j = 0;
    $count;
    $m1 = -1; $m2 = -1;
 
    // Since there are 2n elements,
    // median will be average of elements
    // at index n-1 and n in the array
    // obtained after merging ar1 and ar2
    for ($count = 0; $count <= $n; $count++)
    {
        // Below is to handle case where
        // all elements of ar1[] are smaller
        // than smallest(or first) element of ar2[]
        if ($i == $n)
        {
            $m1 = $m2;
            $m2 = $ar2[0];
            break;
        }
 
        // Below is to handle case where all
        // elements of ar2[] are smaller than
        // smallest(or first) element of ar1[]
        else if ($j == $n)
        {
            $m1 = $m2;
            $m2 = $ar1[0];
            break;
        }
        // equals sign because if two
        // arrays have some common elements
        if ($ar1[$i] <= $ar2[$j])
        {
            // Store the prev median
            $m1 = $m2;
            $m2 = $ar1[$i];
            $i++;
        }
        else
        {
            // Store the prev median
            $m1 = $m2;
            $m2 = $ar2[$j];
            $j++;
        }
    }
 
    return ($m1 + $m2) / 2;
}
 
// Driver Code
$ar1 = array(1, 12, 15, 26, 38);
$ar2 = array(2, 13, 17, 30, 45);
 
$n1 = sizeof($ar1);
$n2 = sizeof($ar2);
if ($n1 == $n2)
    echo("Median is " .
          getMedian($ar1, $ar2, $n1));
else
    echo("Doesn't work for arrays".
         "of unequal size");
 
// This code is contributed by Ajit.
?>


Javascript




<script>
 
// A Simple Merge based O(n) solution to find median of
// two sorted arrays
 
/* This function returns median of ar1[] and ar2[].
Assumptions in this function:
Both ar1[] and ar2[] are sorted arrays
Both have n elements */
function getMedian(ar1, ar2, n)
{
    var i = 0; /* Current index of i/p array ar1[] */
    var j = 0; /* Current index of i/p array ar2[] */
    var count;
    var m1 = -1, m2 = -1;
 
    /* Since there are 2n elements, median will be average
    of elements at index n-1 and n in the array obtained after
    merging ar1 and ar2 */
    for (count = 0; count <= n; count++)
    {
        /*Below is to handle case where all elements of ar1[] are
        smaller than smallest(or first) element of ar2[]*/
        if (i == n)
        {
            m1 = m2;
            m2 = ar2[0];
            break;
        }
 
        /*Below is to handle case where all elements of ar2[] are
        smaller than smallest(or first) element of ar1[]*/
        else if (j == n)
        {
            m1 = m2;
            m2 = ar1[0];
            break;
        }
        /* equals sign because if two
            arrays have some common elements */
        if (ar1[i] <= ar2[j])
        {
            m1 = m2; /* Store the prev median */
            m2 = ar1[i];
            i++;
        }
        else
        {
            m1 = m2; /* Store the prev median */
            m2 = ar2[j];
            j++;
        }
    }
 
    return (m1 + m2)/2;
}
 
/* Driver program to test above function */
var ar1 = [1, 12, 15, 26, 38];
var ar2 = [2, 13, 17, 30, 45];
var n1 = ar1.length;
var n2 = ar2.length;
if (n1 == n2)
    document.write("Median is "+ getMedian(ar1, ar2, n1));
else
    document.write("Doesn't work for arrays of unequal size");
 
</script>


Output

Median is 16
 

Time Complexity: O(n)
Auxiliary Space: O(1)\

Method 2 (By Merging two arrays w/o extra space)

This method works by merging two arrays without extra space and then sorting them.

Algorithm : 

1) Merge the two input arrays ar1[] and ar2[].
2) Sort ar1[] and ar2[] respectively.
3) The median will be the last element of ar1[] + the first
   element of ar2[] divided by 2. [(ar1[n-1] + ar2[0])/2].

Below is the implementation of the above approach:

C++




// CPP program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
/* This function returns
median of ar1[] and ar2[].
Assumptions in this function:
Both ar1[] and ar2[]
are sorted arrays
Both have n elements */
int getMedian(int ar1[], int ar2[], int n)
{
    int j = 0;
    int i = n - 1;
    while (ar1[i] > ar2[j] && j < n && i > -1)
        swap(ar1[i--], ar2[j++]);
    sort(ar1, ar1 + n);
    sort(ar2, ar2 + n);
    return (ar1[n - 1] + ar2[0]) / 2;
}
 
// Driver Code
int main()
{
    int ar1[] = { 1, 12, 15, 26, 38 };
    int ar2[] = { 2, 13, 17, 30, 45 };
 
    int n1 = sizeof(ar1) / sizeof(ar1[0]);
    int n2 = sizeof(ar2) / sizeof(ar2[0]);
    if (n1 == n2)
        cout << "Median is " << getMedian(ar1, ar2, n1);
    else
        cout << "Doesn't work for arrays"
            << " of unequal size";
    getchar();
    return 0;
}
 
// This code is contributed
// by Lakshay


C




// C program for the above approach
#include <stdio.h>
#include <stdlib.h>
 
/* This function returns
median of ar1[] and ar2[].
Assumptions in this function:
Both ar1[] and ar2[]
are sorted arrays
Both have n elements */
 
// compare function, compares two elements
int compare(const void* num1, const void* num2)
{
    if (*(int*)num1 > *(int*)num2)
        return 1;
    else
        return -1;
}
 
int getMedian(int ar1[], int ar2[], int n)
{
    int j = 0;
    int i = n - 1;
    while (ar1[i] > ar2[j] && j < n && i > -1) {
        int temp = ar1[i];
        ar1[i] = ar2[j];
        ar2[j] = temp;
        i--;
        j++;
    }
 
    qsort(ar1, n, sizeof(int), compare);
    qsort(ar2, n, sizeof(int), compare);
 
    return (ar1[n - 1] + ar2[0]) / 2;
}
 
// Driver Code
int main()
{
    int ar1[] = { 1, 12, 15, 26, 38 };
    int ar2[] = { 2, 13, 17, 30, 45 };
 
    int n1 = sizeof(ar1) / sizeof(ar1[0]);
    int n2 = sizeof(ar2) / sizeof(ar2[0]);
    if (n1 == n2)
        printf("Median is %d ", getMedian(ar1, ar2, n1));
    else
        printf("Doesn't work for arrays of unequal size");
    return 0;
}
 
// This code is contributed by Deepthi


Java




/*package whatever //do not write package name here */
import java.io.*;
import java.util.*;
class GFG
{
 
/* This function returns
    median of ar1[] and ar2[].
    Assumptions in this function:
    Both ar1[] and ar2[]
    are sorted arrays
    Both have n elements */
public static int getMedian(int ar1[],
                            int ar2[], int n)
{
    int j = 0;
    int i = n - 1;
    while (ar1[i] > ar2[j] && j < n && i > -1)
    {
    int temp = ar1[i];
    ar1[i] = ar2[j];
    ar2[j] = temp;
    i--; j++;
    }
    Arrays.sort(ar1);
    Arrays.sort(ar2);
    return (ar1[n - 1] + ar2[0]) / 2;
}
 
// Driver code
public static void main (String[] args)
{
    int ar1[] = { 1, 12, 15, 26, 38 };
    int ar2[] = { 2, 13, 17, 30, 45 };
 
    int n1 = 5;
    int n2 = 5;
    if (n1 == n2)
    System.out.println("Median is "+ getMedian(ar1, ar2, n1));
    else
    System.out.println("Doesn't work for arrays of unequal size");
}
}
 
// This code is contributed by Manu Pathria


Python3




# Python program for above approach
 
# function to return median of the arrays
# both are sorted & of same size
def getMedian(ar1, ar2, n):
    i, j = n - 1, 0
 
    # while loop to swap all smaller numbers to arr1
    while(ar1[i] > ar2[j] and i > -1 and j < n):
        ar1[i], ar2[j] = ar2[j], ar1[i]
        i -= 1
        j += 1
 
    ar1.sort()
    ar2.sort()
 
    return (ar1[-1] + ar2[0]) >> 1
 
 
# Driver program
if __name__ == '__main__':
    ar1 = [1, 12, 15, 26, 38]
    ar2 = [2, 13, 17, 30, 45]
 
    n1, n2 = len(ar1), len(ar2)
 
    if(n1 == n2):
        print('Median is', getMedian(ar1, ar2, n1))
    else:
        print("Doesn't work for arrays of unequal size")
 
# This code is contributed by saitejagampala


C#




/*package whatever //do not write package name here */
using System;
public class GFG
{
 
/* This function returns
    median of ar1[] and ar2[].
    Assumptions in this function:
    Both ar1[] and ar2[]
    are sorted arrays
    Both have n elements */
public static int getMedian(int []ar1,
                            int []ar2, int n)
{
    int j = 0;
    int i = n - 1;
    while (ar1[i] > ar2[j] && j < n && i > -1)
    {
    int temp = ar1[i];
    ar1[i] = ar2[j];
    ar2[j] = temp;
    i--; j++;
    }
    Array.Sort(ar1);
    Array.Sort(ar2);
    return (ar1[n - 1] + ar2[0]) / 2;
}
 
// Driver code
public static void Main(String[] args)
{
    int []ar1 = { 1, 12, 15, 26, 38 };
    int []ar2 = { 2, 13, 17, 30, 45 };
 
    int n1 = 5;
    int n2 = 5;
    if (n1 == n2)
    Console.WriteLine("Median is "+ getMedian(ar1, ar2, n1));
    else
    Console.WriteLine("Doesn't work for arrays of unequal size");
}
}
 
// This code is contributed by aashish1995


Javascript




<script>
 
    /* This function returns
    median of ar1[] and ar2[].
    Assumptions in this function:
    Both ar1[] and ar2[]
    are sorted arrays
    Both have n elements */
    function getMedian(ar1, ar2, n)
    {
    let j = 0;
    let i = n - 1;
    while (ar1[i] > ar2[j] && j < n && i > -1)
    {
        let temp = ar1[i];
        ar1[i] = ar2[j];
        ar2[j] = temp;
        i--; j++;
    }
    ar1.sort(function(a, b){return a - b});
    ar2.sort(function(a, b){return a - b});
    return parseInt((ar1[n - 1] + ar2[0]) / 2, 10);
    }
     
    let ar1 = [ 1, 12, 15, 26, 38 ];
    let ar2 = [ 2, 13, 17, 30, 45 ];
 
    let n1 = 5;
    let n2 = 5;
    if (n1 == n2)
    document.write("Median is "+ getMedian(ar1, ar2, n1));
    else
    document.write("Doesn't work for arrays of unequal size");
     
</script>


Output

Median is 16

Time Complexity: O(nlogn)
Auxiliary Space: O(1)

 

Method 3 (Using binary search)

This method can also be used for arrays of different sizes.

Algorithm:

We can find the kth element by using binary search on whole range of constraints of elements.

  • Initialize ans = 0.0
  • Initialize low = -10^9, high = 10^9 and pos = n
  • Run a loop while(low <= high):
    • Calculate mid = (low + (high – low)>>1)
    • Find total elements less or equal to mid in the given arrays
    • If the count is less or equal to pos
      • Update low = mid + 1
      • Else high = mid – 1
  • Store low in ans, i.e., ans = low.
  • Again follow step3 with pos as n – 1
  • Return (sum + low * 1.0)/2

Below is the implementation of the above approach:

C++




#include <bits/stdc++.h>
using namespace std;
 
double getMedian(int arr1[], int arr2[], int n)
{
    // according to given constraints all numbers are in
    // this range
    int low = (int)-1e9, high = (int)1e9;
 
    int pos = n;
    double ans = 0.0;
    // binary search to find the element which will be
    // present at pos = totalLen/2 after merging two
    // arrays in sorted order
    while (low <= high) {
        int mid = low + ((high - low) >> 1);
 
        // total number of elements in arrays which are
        // less than mid
        int ub = upper_bound(arr1, arr1 + n, mid) - arr1
                 + upper_bound(arr2, arr2 + n, mid) - arr2;
 
        if (ub <= pos)
            low = mid + 1;
        else
            high = mid - 1;
    }
 
    ans = low;
 
    // As there are even number of elements, we will
    // also have to find element at pos = totalLen/2 - 1
    pos--;
    low = (int)-1e9;
    high = (int)1e9;
    while (low <= high) {
        int mid = low + ((high - low) >> 1);
        int ub = upper_bound(arr1, arr1 + n, mid) - arr1
                 + upper_bound(arr2, arr2 + n, mid) - arr2;
 
        if (ub <= pos)
            low = mid + 1;
        else
            high = mid - 1;
    }
 
    // average of two elements in case of even
    // number of elements
    ans = (ans + low) / 2;
 
    return ans;
}
 
int main()
{
    int arr1[] = { 1, 4, 5, 6, 10 };
    int arr2[] = { 2, 3, 4, 5, 7 };
 
    int n = sizeof(arr1) / sizeof(arr1[0]);
 
    double median = getMedian(arr1, arr2, n);
 
    cout << "Median is " << median << endl;
 
    return 0;
}
// This code is contributed by Srj_27


Java




/*package whatever //do not write package name here */
 
import java.io.*;
 
class GFG {
 
    public static double getMedian(int[] nums1, int[] nums2,
                                   int n)
    {
        // according to given constraints all numbers are in
        // this range
        int low = (int)-1e9, high = (int)1e9;
 
        int pos = n;
        double ans = 0.0;
        // binary search to find the element which will be
        // present at pos = totalLen/2 after merging two
        // arrays in sorted order
        while (low <= high) {
            int mid = low + ((high - low) >> 1);
 
            // total number of elements in arrays which are
            // less than mid
            int ub = upperBound(nums1, mid)
                     + upperBound(nums2, mid);
 
            if (ub <= pos)
                low = mid + 1;
            else
                high = mid - 1;
        }
 
        ans = low;
 
        // As there are even number of elements, we will
        // also have to find element at pos = totalLen/2 - 1
        pos--;
        low = (int)-1e9;
        high = (int)1e9;
        while (low <= high) {
            int mid = low + ((high - low) >> 1);
            int ub = upperBound(nums1, mid)
                     + upperBound(nums2, mid);
 
            if (ub <= pos)
                low = mid + 1;
            else
                high = mid - 1;
        }
 
        // average of two elements in case of even
        // number of elements
        ans = (ans + low * 1.0) / 2;
 
        return ans;
    }
 
    // a function which returns the index of smallest
    // element which is strictly greater than key (i.e. it
    // returns number of elements which are less than or
    // equal to key)
    public static int upperBound(int[] arr, int key)
    {
        int low = 0, high = arr.length;
 
        while (low < high) {
            int mid = low + ((high - low) >> 1);
 
            if (arr[mid] <= key)
                low = mid + 1;
            else
                high = mid;
        }
 
        return low;
    }
 
    public static void main(String[] args)
    {
        int[] arr = { 1, 4, 5, 6, 10 };
        int[] brr = { 2, 3, 4, 5, 7 };
 
        double median = getMedian(arr, brr, arr.length);
 
        System.out.println("Median is " + median);
    }
}


C#




// Include namespace system
using System;
 
 
public class GFG
{
    public static double getMedian(int[] nums1, int[] nums2, int n)
    {
        // according to given constraints all numbers are in
        // this range
        var low = (int)-1.0E9;
        var high = (int)1.0E9;
        var pos = n;
        var ans = 0.0;
        // binary search to find the element which will be
        // present at pos = totalLen/2 after merging two
        // arrays in sorted order
        while (low <= high)
        {
            var mid = low + ((high - low) >> 1);
            // total number of elements in arrays which are
            // less than mid
            var ub = upperBound(nums1, mid) + upperBound(nums2, mid);
            if (ub <= pos)
            {
                low = mid + 1;
            }
            else
            {
                high = mid - 1;
            }
        }
        ans = low;
        // As there are even number of elements, we will
        // also have to find element at pos = totalLen/2 - 1
        pos--;
        low = (int)-1.0E9;
        high = (int)1.0E9;
        while (low <= high)
        {
            var mid = low + ((high - low) >> 1);
            var ub = upperBound(nums1, mid) + upperBound(nums2, mid);
            if (ub <= pos)
            {
                low = mid + 1;
            }
            else
            {
                high = mid - 1;
            }
        }
        // average of two elements in case of even
        // number of elements
        ans = (ans + low * 1.0) / 2;
        return ans;
    }
    // a function which returns the index of smallest
    // element which is strictly greater than key (i.e. it
    // returns number of elements which are less than or
    // equal to key)
    public static int upperBound(int[] arr, int key)
    {
        var low = 0;
        var high = arr.Length;
        while (low < high)
        {
            var mid = low + ((high - low) >> 1);
            if (arr[mid] <= key)
            {
                low = mid + 1;
            }
            else
            {
                high = mid;
            }
        }
        return low;
    }
    public static void Main(String[] args)
    {
        int[] arr = {1, 4, 5, 6, 10};
        int[] brr = {2, 3, 4, 5, 7};
        var median = getMedian(arr, brr, arr.Length);
        Console.WriteLine("Median is " + median.ToString());
    }
}


Python




# Calculate the number of elements less than or equal to mid in the given arrays
def count_less_than_or_equal_to_mid(mid, arrays):
    count = 0
    for array in arrays:
        count += len([x for x in array if x <= mid])
    return count
 
def find_kth_element(arrays, n):
    ans = 0.0
    low = -1e9
    high = 1e9
    pos = n
 
    # Binary search to find the kth element
    while low <= high:
        mid = low + (high - low) // 2
        count = count_less_than_or_equal_to_mid(mid, arrays)
        if count <= pos:
            low = mid + 1
        else:
            high = mid - 1
 
    ans = low
 
    # Update pos and repeat the binary search to find the (n-1)th element
    pos = n - 1
    low = -1e9
    high = 1e9
    while low <= high:
        mid = low + (high - low) // 2
        count = count_less_than_or_equal_to_mid(mid, arrays)
        if count <= pos:
            low = mid + 1
        else:
            high = mid - 1
 
    ans += low
 
    # Return the average of the two elements
    return (ans / 2.0)
 
# Test with some arrays
arrays = [[1, 4, 5, 6, 10], [2, 3, 4, 5, 7]]
n = 5
print("Median in", find_kth_element(arrays, n)) 
 
#code is contributed by khushboogoyal499


Javascript




// Define the function getMedian to find the median of two arrays
function getMedian(arr1, arr2, n) {
  // Define the variables low, high, pos and ans
  // According to given constraints, all numbers are in this range
  let low = -1e9,
    high = 1e9,
    pos = n,
    ans = 0.0;
 
  // Binary search to find the element which will be
  // present at pos = totalLen/2 after merging two
  // arrays in sorted order
  while (low <= high) {
    let mid = low + ((high - low) >> 1);
 
    // Total number of elements in arrays which are
    // less than mid
    // Note: The function upper_bound is not available in JavaScript
    // You need to find an equivalent solution or implement it yourself
    let ub = 0;
 
    if (ub <= pos) {
      low = mid + 1;
    } else {
      high = mid - 1;
    }
  }
 
  ans = low;
 
  // As there are even number of elements, we will
  // also have to find element at pos = totalLen/2 - 1
  pos--;
  low = -1e9;
  high = 1e9;
  while (low <= high) {
    let mid = low + ((high - low) >> 1);
    let ub = 0;
 
    if (ub <= pos) {
      low = mid + 1;
    } else {
      high = mid - 1;
    }
  }
 
  // Average of two elements in case of even
  // number of elements
  ans = (ans + low) / 2;
 
  return ans;
}
 
// Main function
function main() {
  let arr1 = [1, 4, 5, 6, 10];
  let arr2 = [2, 3, 4, 5, 7];
 
  let n = arr1.length;
 
  let median = getMedian(arr1, arr2, n);
 
  console.log("Median is " + median);
 
  return 0;
}
 
// Call the main function
main();
 
// This code is contributed by Vikram_Shirsat


Output

Median is 4.5

Time Complexity: O(log n)
Auxiliary Space: O(1)

Median of two sorted arrays of different sizes

Please write comments if you find the above codes/algorithms incorrect, or find other ways to solve the same problem.



Previous Article
Next Article

Similar Reads

Check if two sorted arrays can be merged to form a sorted array with no adjacent pair from the same array
Given two sorted arrays A[] and B[] of size N, the task is to check if it is possible to merge two given sorted arrays into a new sorted array such that no two consecutive elements are from the same array. Examples: Input: A[] = {3, 5, 8}, B[] = {2, 4, 6}Output: Yes Explanation: Merged array = {B[0], A[0], B[1], A[1], B[2], A[2]} Since the resultan
15+ min read
Generate all possible sorted arrays from alternate elements of two given sorted arrays
Given two sorted arrays A and B, generate all possible arrays such that the first element is taken from A then from B then from A, and so on in increasing order till the arrays are exhausted. The generated arrays should end with an element from B. Example: A = {10, 15, 25} B = {1, 5, 20, 30} The resulting arrays are: 10 20 10 20 25 30 10 30 15 20 1
12 min read
Median of two sorted arrays of different sizes | Set 1 (Linear)
This is an extension of the median of two sorted arrays of equal size problem. Here we handle arrays of unequal size also. Examples: Input: a[] = {1, 12, 15, 26, 38} b[] = {2, 13, 24} Output: 14 Explanation: After merging arrays the result is 1, 2, 12, 13, 15, 24, 26, 38 median = (13 + 15)/2 = 14. Input: a[] = {1, 3, 5, 7} b[] = {2, 4, 6, 8} Output
12 min read
Median of two Sorted Arrays of Different Sizes using Binary Search
Given two sorted arrays, a[] and b[] os size n and m, the task is to find the median of these sorted arrays, in O(log(min(n, m)), when n is the number of elements in the first array, and m is the number of elements in the second array. Note: In case of even numbers in total and if we want to return a median that exists in the merged array we can re
15+ min read
Median of two Sorted Arrays of Different Sizes
Given two sorted arrays, a[] and b[], the task is to find the median of these sorted arrays, where N is the number of elements in the first array, and M is the number of elements in the second array. This is an extension of Median of two sorted arrays of equal size problem. Here we handle arrays of unequal size also. Examples: Input: a[] = {-5, 3,
15+ min read
Minimize sum of product of same-indexed elements of two arrays by reversing a subarray of one of the two arrays
Given two equal-length arrays A[] and B[], consisting only of positive integers, the task is to reverse any subarray of the first array such that sum of the product of same-indexed elements of the two arrays, i.e. (A[i] * B[i]) is minimum. Examples: Input: N = 4, A[] = {2, 3, 1, 5}, B[] = {8, 2, 4, 3} Output: A[] = 1 3 2 5 B[] = 8 2 4 3 Minimum pro
12 min read
Find Median for each Array element by excluding the index at which Median is calculated
Given an array A[] of N integers where N is even, . the task is to generate an array of medians where the median of the array is calculated by taking the median of array A[] excluding A[i]-th element. Examples: Input N = 4, A = [2, 4, 4, 3]Output: [4, 3, 3, 4]Explanation: Median after removing A[0]: New sorted array will be [3, 4, 4]. Median = 4. M
10 min read
Count elements of same value placed at same indices of two given arrays
Given two arrays A[] and B[] of N unique elements, the task is to find the maximum number of matched elements from the two given arrays. Elements of the two arrays are matched if they are of the same value and can be placed at the same index (0-based indexing).(By right shift or left shift of the two arrays). Examples: Input: A[] = { 5, 3, 7, 9, 8
8 min read
Bitwise XOR of same indexed array elements after rearranging an array to make XOR of same indexed elements of two arrays equal
Given two arrays A[] and B[] consisting of N positive integers, the task is to the Bitwise XOR of same indexed array elements after rearranging the array B[] such that the Bitwise XOR of the same indexed elements of the arrays A[] becomes equal. Examples: Input: A[] = {1, 2, 3}, B[] = {4, 6, 7}Output: 5Explanation:Below are the possible arrangement
14 min read
Maximize median of Array formed by adding elements of two other Arrays
Given two arrays x[] and y[] of N integers, the task is to form an array z[] of x[i] + y[j], (0 ?i, j &lt; N) and find the max value of median of z[] formed by optimal rearrangement. Examples: Input: N = 5, x[] = {1, 2, 3, 5, 6}, y[] = {4, 7, 0, 9, 8}Output: 12Explanation: Let, z[] = { 1+0, 2+4, 5+7, 3+9, 6+8} = {1, 6, 12, 12, 14} to get maximum Me
6 min read