Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Practice Divide and Conquer
  • MCQs on Divide and Conquer
  • Tutorial on Divide & Conquer
  • Binary Search
  • Merge Sort
  • Quick Sort
  • Calculate Power
  • Strassen's Matrix Multiplication
  • Karatsuba Algorithm
  • Divide and Conquer Optimization
  • Closest Pair of Points
Open In App
Next Article:
Longest Increasing Subsequence Size (N log N)
Next article icon

Median of two Sorted Arrays of Different Sizes

Last Updated : 27 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

Given two sorted arrays, a[] and b[], the task is to find the median of these sorted arrays. Assume that the two sorted arrays are merged and then median is selected from the combined 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, 6, 12, 15], b[] = [-12, -10, -6, -3, 4, 10]
Output: 3
Explanation: The merged array is [-12, -10, -6, -5 , -3, 3, 4, 6, 10, 12, 15]. So the median of the merged array is 3.

Input: a[] = [1, 12, 15, 26, 38], b[] = [2, 13, 17, 30, 45, 60]
Output: The median is 17.
Explanation : The merged array is [1, 2, 12, 13, 15, 17, 26, 30, 38, 45, 60]. So the median of the merged array is 17.

Input: a[] = [], b[] = [2, 4, 5, 6]
Output: The median is 4.5
Explanation: The merged array is [2, 4, 5, 6]. The total number of elements are even, so there are two middle elements. Take the average between the two: (4 + 5) / 2 = 4.5

Table of Content

  • [Naive Approach] Using Sorting – O((n + m) * log (n + m)) Time and O(n + m) Space
  • [Better Approach] Use Merge of Merge Sort – O(m + n) Time and O(1) Space
  • [Expected Approach] Using Binary Search – O(log(min(n, m)) Time and O(1) Space

[Naive Approach] Using Sorting – O((n + m) * log (n + m)) Time and O(n + m) Space

The idea is to concatenate both the arrays into a new array, sort the new array and return the middle of the new sorted array.

Illustration:

a[] = [ -5, 3, 6, 12, 15 ], b[] = [ -12, -10, -6, -3, 4, 10 ]

  • After concatenating them in a third array: c[] = [ -5, 3, 6, 12, 15, -12, -10, -6, -3, 4, 10]
  • Sort c[] = [ -12, -10, -6, -5, -3, 3, 4, 6, 10, 12, 15 ]
  • As the length of c[] is odd, so the median is the middle element = 3
C++
// C++ Code to find Median of two Sorted Arrays of  // Different Sizes using Sorting  #include <iostream> #include <vector> #include <algorithm> using namespace std;  double medianOf2(vector<int>& a, vector<int>& b) {        // Merge both the arrays     vector<int> c(a.begin(), a.end());     c.insert(c.end(), b.begin(), b.end());      // Sort the concatenated array     sort(c.begin(), c.end());          int len = c.size();   	   	// If length of array is even     if (len % 2 == 0)          return (c[len / 2] + c[len / 2 - 1]) / 2.0;      	// If length of array is odd   	else          return c[len / 2]; }  int main() {     vector<int> a = { -5, 3, 6, 12, 15 };     vector<int> b = { -12, -10, -6, -3, 4, 10 };      cout << medianOf2(a, b) << endl;     return 0; } 
C
// C Code to find Median of two Sorted Arrays of  // Different Sizes using Sorting  #include <stdio.h>  // Function to compare two integers for qsort int compare(const void *a, const void *b) {     return (*(int*)a - *(int*)b); }  double medianOf2(int a[], int n, int b[], int m) {        	// Calculate the total size of the concatenated array     int len = n + m;          int c[len];          // Concatenate a and b into c     for (int i = 0; i < n; ++i)         c[i] = a[i];      for (int i = 0; i < m; ++i)         c[n + i] = b[i];          // Sort the concatenated array     qsort(c, len, sizeof(int), compare);          // Calculate and return the median     int mid = len / 2;        	// If length of array is even     if (len % 2 == 0)          return (c[mid] + c[mid - 1]) / 2.0;      	// If length of array is odd   	else          return c[mid]; }  int main() {     int a[] = { -5, 3, 6, 12, 15 };     int b[] = { -12, -10, -6, -3, 4, 10 };          int n = sizeof(a) / sizeof(a[0]);     int m = sizeof(b) / sizeof(b[0]);          printf("%f\n", medianOf2(a, n, b, m));          return 0; } 
Java
// Java Code to find Median of two Sorted Arrays of  // Different Sizes using Sorting  import java.util.*;  class GfG {     static double medianOf2(int[] a, int[] b) {          // Merge both the arrays         int[] c = new int[a.length + b.length];         System.arraycopy(a, 0, c, 0, a.length);         System.arraycopy(b, 0, c, a.length, b.length);          // Sort the concatenated array         Arrays.sort(c);          int len = c.length;          // If length of array is even         if (len % 2 == 0)             return (c[len / 2] + c[len / 2 - 1]) / 2.0;          // If length of array is odd         else             return c[len / 2];     }      public static void main(String[] args) {         int[] a = { -5, 3, 6, 12, 15 };         int[] b = { -12, -10, -6, -3, 4, 10 };          System.out.println(medianOf2(a, b));     } } 
Python
# Python Code to find Median of two Sorted Arrays of  # Different Sizes using Sorting  def medianOf2(a, b):     # Merge both the arrays     c = a + b      # Sort the concatenated array     c.sort()      len_c = len(c)      # If length of array is even     if len_c % 2 == 0:         return (c[len_c // 2] + c[len_c // 2 - 1]) / 2.0      # If length of array is odd     else:         return c[len_c // 2]  if __name__ == "__main__":     a = [-5, 3, 6, 12, 15]     b = [-12, -10, -6, -3, 4, 10]      print(medianOf2(a, b)) 
C#
// C# Code to find Median of two Sorted Arrays of  // Different Sizes using Sorting  using System; using System.Linq;  class GfG {     static double MedianOf2(int[] a, int[] b) {            // Merge both the arrays         int[] c = a.Concat(b).ToArray();          // Sort the concatenated array         Array.Sort(c);              int len = c.Length;                  // If length of array is even         if (len % 2 == 0)              return (c[len / 2] + c[len / 2 - 1]) / 2.0;            // If length of array is odd         else              return c[len / 2];     }      static void Main() {         int[] a = { -5, 3, 6, 12, 15 };         int[] b = { -12, -10, -6, -3, 4, 10 };          Console.WriteLine(MedianOf2(a, b));     } } 
JavaScript
// JavaScript Code to find Median of two Sorted Arrays of  // Different Sizes using Sorting  function medianOf2(a, b) {      // Merge both the arrays     let c = [...a, ...b];      // Sort the concatenated array     c.sort((x, y) => x - y);      let len = c.length;      // If length of array is even     if (len % 2 === 0)          return (c[len / 2] + c[len / 2 - 1]) / 2.0;      // If length of array is odd     else          return c[Math.floor(len / 2)]; }  // Driver Code let a = [-5, 3, 6, 12, 15]; let b = [-12, -10, -6, -3, 4, 10];  console.log(medianOf2(a, b)); 

Output
3 

Time Complexity: O((n + m)*log (n + m)), as we are sorting the merged array of size n + m.
Auxiliary Space: O(n + m), for storing the merged array.

[Better Approach] Use Merge of Merge Sort – O(m + n) Time and O(1) Space

The given arrays are sorted, so merge the sorted arrays in an efficient way and keep the count of elements merged so far. So when we reach half of the total, print the median. There can be two cases: 

  • Case 1: m+n is odd, the median is the ((m+n)/2)th element while merging the arrays.
  • Case 2: m+n is even, the median will be the average of ((m+n)/2 – 1)th and ((m+n)/2)th element while merging the arrays.
C++
// C++ Code to find the median of two sorted arrays // using Merge of Merge Sort  #include <iostream> #include <vector> using namespace std;  double medianOf2(vector<int>& a, vector<int>& b) {     int n = a.size(), m = b.size();     int i = 0, j = 0;      	// m1 to store the middle element   	// m2 to store the second middle element     int m1 = -1, m2 = -1;      // Loop till (m+n)/2     for (int count = 0; count <= (m + n) / 2; count++) {         m2 = m1;             	// If both the arrays have remaining elements         if (i != n && j != m)             m1 = (a[i] > b[j]) ? b[j++] : a[i++];                	// If only a[] has remaining elements       	else if (i < n)              m1 = a[i++];              	// If only b[] has remaining elements         else              m1 = b[j++];     }      // Return median based on odd/even size     if ((m + n) % 2 == 1)          return m1;     else         return (m1 + m2) / 2.0; }  int main() {     vector<int> arr1 = { -5, 3, 6, 12, 15};     vector<int> arr2 = { -12, -10, -6, -3, 4, 10 };      cout << medianOf2(arr1, arr2) << endl;     return 0; } 
C
// C Code to find the median of two sorted arrays // using Merge of Merge Sort  #include <stdio.h>  double medianOf2(int a[], int n, int b[], int m) {     int i = 0, j = 0;        // m1 to store the middle element     // m2 to store the second middle element     int m1 = -1, m2 = -1;      // Loop till (m+n)/2     for (int count = 0; count <= (m + n) / 2; count++) {         m2 = m1;                // If both the arrays have remaining elements         if (i != n && j != m)             m1 = (a[i] > b[j]) ? b[j++] : a[i++];                  // If only a[] has remaining elements         else if (i < n)              m1 = a[i++];                // If only b[] has remaining elements         else              m1 = b[j++];     }      // Return median based on odd/even size     if ((m + n) % 2 == 1)          return m1;     else         return (m1 + m2) / 2.0; }  int main() {     int arr1[] = { -5, 3, 6, 12, 15 };     int arr2[] = { -12, -10, -6, -3, 4, 10 };          int n = sizeof(arr1) / sizeof(arr1[0]);     int m = sizeof(arr2) / sizeof(arr2[0]);      printf("%f\n", medianOf2(arr1, n, arr2, m));     return 0; } 
Java
// Java Code to find the median of two sorted arrays // using Merge of Merge Sort  import java.util.*;  class GfG {     static double medianOf2(int[] a, int[] b) {         int n = a.length, m = b.length;         int i = 0, j = 0;                // m1 to store the middle element         // m2 to store the second middle element         int m1 = -1, m2 = -1;          // Loop till (m + n)/2         for (int count = 0; count <= (m + n) / 2; count++) {             m2 = m1;                        // If both the arrays have remaining elements             if (i != n && j != m)                 m1 = (a[i] > b[j]) ? b[j++] : a[i++];                          // If only a[] has remaining elements             else if (i < n)                  m1 = a[i++];                        // If only b[] has remaining elements             else                  m1 = b[j++];         }          // Return median based on odd/even size         if ((m + n) % 2 == 1)              return m1;         else             return (m1 + m2) / 2.0;     }      public static void main(String[] args) {         int[] arr1 = { -5, 3, 6, 12, 15 };         int[] arr2 = { -12, -10, -6, -3, 4, 10 };          System.out.println(medianOf2(arr1, arr2));     } } 
Python
# Python Code to find the median of two sorted arrays # using Merge of Merge Sort  def medianOf2(a, b):     n = len(a)     m = len(b)     i = 0     j = 0      # m1 to store the middle element     # m2 to store the second middle element     m1 = -1     m2 = -1      # Loop till (m+n)/2     for count in range((m + n) // 2 + 1):         m2 = m1          # If both the arrays have remaining elements         if i != n and j != m:             if a[i] > b[j]:                 m1 = b[j]                 j += 1             else:                 m1 = a[i]                 i += 1          # If only a[] has remaining elements         elif i < n:             m1 = a[i]             i += 1          # If only b[] has remaining elements         else:             m1 = b[j]             j += 1      # Return median based on odd/even size     if (m + n) % 2 == 1:         return m1     else:         return (m1 + m2) / 2.0   if __name__ == "__main__":     arr1 = [-5, 3, 6, 12, 15]     arr2 = [-12, -10, -6, -3, 4, 10]      print(medianOf2(arr1, arr2)) 
C#
// C# Code to find the median of two sorted arrays // using Merge of Merge Sort  using System;  class GfG {     static double medianOf2(int[] a, int[] b) {         int n = a.Length, m = b.Length;         int i = 0, j = 0;          // m1 to store the middle element         // m2 to store the second middle element         int m1 = -1, m2 = -1;          // Loop till (m+n)/2         for (int count = 0; count <= (m + n) / 2; count++) {             m2 = m1;              // If both the arrays have remaining elements             if (i != n && j != m)                 m1 = (a[i] > b[j]) ? b[j++] : a[i++];              // If only a[] has remaining elements             else if (i < n)                 m1 = a[i++];              // If only b[] has remaining elements             else                 m1 = b[j++];         }          // Return median based on odd/even size         if ((m + n) % 2 == 1)             return m1;         else             return (m1 + m2) / 2.0;     }      static void Main() {         int[] arr1 = { -5, 3, 6, 12, 15 };         int[] arr2 = { -12, -10, -6, -3, 4, 10 };          Console.WriteLine(medianOf2(arr1, arr2));     } } 
JavaScript
// JavaScript Code to find the median of two sorted arrays // using Merge of Merge Sort  function medianOf2(a, b) {     let n = a.length, m = b.length;     let i = 0, j = 0;      // m1 to store the middle element     // m2 to store the second middle element     let m1 = -1, m2 = -1;      // Loop till (m+n)/2     for (let count = 0; count <= (m + n) / 2; count++) {         m2 = m1;          // If both the arrays have remaining elements         if (i != n && j != m)             m1 = (a[i] > b[j]) ? b[j++] : a[i++];          // If only a[] has remaining elements         else if (i < n)              m1 = a[i++];          // If only b[] has remaining elements         else              m1 = b[j++];     }      // Return median based on odd/even size     if ((m + n) % 2 === 1)          return m1;     else         return (m1 + m2) / 2.0; }  // Driver Code let arr1 = [-5, 3, 6, 12, 15]; let arr2 = [-12, -10, -6, -3, 4, 10];  console.log(medianOf2(arr1, arr2)); 

Output
3 

Time Complexity: O(n + m), where n and m are lengths of a[] and b[] respectively.
Auxiliary Space: O(1), No extra space is required.

[Expected Approach] Using Binary Search – O(log(min(n, m)) Time and O(1) Space

Prerequisite: Median of two sorted arrays of same size

The approach is similar to the Binary Search approach of Median of two sorted arrays of same size with the only difference that here we apply binary search on the smaller array instead of a[].

  • Consider the first array is smaller. If first array is greater, then swap the arrays to make sure that the first array is smaller.
  • We mainly maintain two sets in this algorithm by doing binary search in the smaller array. Let mid1 be the partition of the smaller array. The first set contains elements from 0 to (mid1 – 1) from smaller array and mid2 = ((n + m + 1) / 2 – mid1) elements from the greater array to make sure that the first set has exactly (n+m+1)/2 elements. The second set contains remaining half elements.
  • Our target is to find a point in both arrays such that all elements in the first set are smaller than all elements in the elements in the other set (set that contains elements from right side). For this we validate the partitions using the same way as we did in Median of two sorted arrays of same size.

Why do we apply Binary Search on the smaller array?

Applying Binary Search on the smaller array helps us in two ways:

  • Since we are applying binary search on the smaller array, we have optimized the time complexity of the algorithm from O(logn) to O(log(min(n, m)).
  • Also, if we don’t apply the binary search on the smaller array, then then we need to set low = max(0, (n + m + 1)/2 – m) and high = min(n, (n + m + 1)/2) to avoid partitioning mid1 or mid2 outside a[] or b[] respectively.

To avoid handling such cases, we can simply binary search on the smaller array.


C++
// C++ Program to find the median of two sorted arrays // of different size using Binary Search  #include <iostream> #include <vector> #include <limits.h> using namespace std;  double medianOf2(vector<int> &a, vector<int> &b) {     int n = a.size(), m = b.size(); 	   	// If a[] has more elements, then call medianOf2    	// with reversed parameters     if (n > m)         return medianOf2(b, a);        int lo = 0, hi = n;     while (lo <= hi) {         int mid1 = (lo + hi) / 2;         int mid2 = (n + m + 1) / 2 - mid1;          // Find elements to the left and right of partition in a[]         int l1 = (mid1 == 0 ? INT_MIN : a[mid1 - 1]);         int r1 = (mid1 == n ? INT_MAX : a[mid1]);          // Find elements to the left and right of partition in b[]         int l2 = (mid2 == 0 ? INT_MIN : b[mid2 - 1]);         int r2 = (mid2 == m ? INT_MAX : b[mid2]);          // If it is a valid partition         if (l1 <= r2 && l2 <= r1) {                      	// If the total elements are even, then median is            	// the average of two middle elements             if ((n + m) % 2 == 0)                 return (max(l1, l2) + min(r1, r2)) / 2.0;                      	// If the total elements are odd, then median is           	// the middle element             else                 return max(l1, l2);         }          // Check if we need to take lesser elements from a[]         if (l1 > r2)             hi = mid1 - 1;                // Check if we need to take more elements from a[]         else             lo = mid1 + 1;     }     return 0; }  int main() {     vector<int> a = {1, 12, 15, 26, 38};     vector<int> b = {2, 13, 17, 30, 45, 60};        cout << medianOf2(a, b);     return 0; } 
C
// C Program to find the median of two sorted arrays // of different size using Binary Search  #include <stdio.h> #include <limits.h>  double medianOf2(int a[], int n, int b[], int m) {      // If a[] has more elements, then call medianOf2     // with reversed parameters     if (n > m)         return medianOf2(b, m, a, n);      int lo = 0, hi = n;     while (lo <= hi) {         int mid1 = (lo + hi) / 2;         int mid2 = (n + m + 1) / 2 - mid1;          // Find elements to the left and right of partition in a[]         int l1 = (mid1 == 0) ? INT_MIN : a[mid1 - 1];         int r1 = (mid1 == n) ? INT_MAX : a[mid1];          // Find elements to the left and right of partition in b[]         int l2 = (mid2 == 0) ? INT_MIN : b[mid2 - 1];         int r2 = (mid2 == m) ? INT_MAX : b[mid2];          // If it is a valid partition         if (l1 <= r2 && l2 <= r1) {                          // If the total elements are even, then median is              // the average of two middle elements             if ((n + m) % 2 == 0)                 return (max(l1, l2) + min(r1, r2)) / 2.0;              // If the total elements are odd, then median is              // the middle element             else                 return max(l1, l2);         }          // Check if we need to take fewer elements from a[]         if (l1 > r2)             hi = mid1 - 1;          // Check if we need to take more elements from a[]         else             lo = mid1 + 1;     }      return 0; }  // Helper functions for max and min int max(int a, int b) {     return a > b ? a : b; }  int min(int a, int b) {     return a < b ? a : b; }  int main() {     int a[] = {1, 12, 15, 26, 38};     int b[] = {2, 13, 17, 30, 45, 60};          int n = sizeof(a) / sizeof(a[0]);     int m = sizeof(b) / sizeof(b[0]);      printf("%f\n", medianOf2(a, n, b, m));     return 0; } 
Java
// Java Program to find the median of two sorted arrays // of different size using Binary Search  import java.util.*;  class GfG {     static double medianOf2(int[] a, int[] b) {         int n = a.length, m = b.length;          // If a[] has more elements, then call medianOf2 with reversed parameters         if (n > m)             return medianOf2(b, a);          int lo = 0, hi = n;         while (lo <= hi) {             int mid1 = (lo + hi) / 2;             int mid2 = (n + m + 1) / 2 - mid1;              // Find elements to the left and right of partition in a[]             int l1 = (mid1 == 0) ? Integer.MIN_VALUE : a[mid1 - 1];             int r1 = (mid1 == n) ? Integer.MAX_VALUE : a[mid1];              // Find elements to the left and right of partition in b[]             int l2 = (mid2 == 0) ? Integer.MIN_VALUE : b[mid2 - 1];             int r2 = (mid2 == m) ? Integer.MAX_VALUE : b[mid2];              // If it is a valid partition             if (l1 <= r2 && l2 <= r1) {                  // If the total elements are even, then median is                  // the average of two middle elements                 if ((n + m) % 2 == 0)                     return (Math.max(l1, l2) + Math.min(r1, r2)) / 2.0;                  // If the total elements are odd, then median is                  // the middle element                 else                     return Math.max(l1, l2);             }              // Check if we need to take fewer elements from a[]             if (l1 > r2)                 hi = mid1 - 1;              // Check if we need to take more elements from a[]             else                 lo = mid1 + 1;         }         return 0;     }      public static void main(String[] args) {         int[] a = {1, 12, 15, 26, 38};         int[] b = {2, 13, 17, 30, 45, 60};          System.out.println(medianOf2(a, b));     } } 
Python
# Python Program to find the median of two sorted arrays # of different size using Binary Search  def medianOf2(a, b):     n = len(a)     m = len(b)      # If a[] has more elements, then call medianOf2      # with reversed parameters     if n > m:         return medianOf2(b, a)      lo = 0     hi = n     while lo <= hi:         mid1 = (lo + hi) // 2         mid2 = (n + m + 1) // 2 - mid1          # Find elements to the left and right of partition in a[]         l1 = (mid1 == 0) and float('-inf') or a[mid1 - 1]         r1 = (mid1 == n) and float('inf') or a[mid1]          # Find elements to the left and right of partition in b[]         l2 = (mid2 == 0) and float('-inf') or b[mid2 - 1]         r2 = (mid2 == m) and float('inf') or b[mid2]          # If it is a valid partition         if l1 <= r2 and l2 <= r1:                        # If the total elements are even, then median is              # the average of two middle elements             if (n + m) % 2 == 0:                 return (max(l1, l2) + min(r1, r2)) / 2.0                            # If the total elements are odd, then median is              # the middle element             else:                 return max(l1, l2)          # Check if we need to take lesser elements from a[]         if l1 > r2:             hi = mid1 - 1                      # Check if we need to take more elements from a[]         else:             lo = mid1 + 1     return 0  if __name__ == "__main__":     a = [1, 12, 15, 26, 38]     b = [2, 13, 17, 30, 45, 60]        print(medianOf2(a, b)) 
C#
// C# Program to find the median of two sorted arrays // of different size using Binary Search  using System;  class GfG {     static double medianOf2(int[] a, int[] b) {         int n = a.Length, m = b.Length;          // If a[] has more elements, then call medianOf2          // with reversed parameters         if (n > m)             return medianOf2(b, a);          int lo = 0, hi = n;         while (lo <= hi) {             int mid1 = (lo + hi) / 2;             int mid2 = (n + m + 1) / 2 - mid1;              // Find elements to the left and right of partition in a[]             int l1 = (mid1 == 0 ? int.MinValue : a[mid1 - 1]);             int r1 = (mid1 == n ? int.MaxValue : a[mid1]);              // Find elements to the left and right of partition in b[]             int l2 = (mid2 == 0 ? int.MinValue : b[mid2 - 1]);             int r2 = (mid2 == m ? int.MaxValue : b[mid2]);              // If it is a valid partition             if (l1 <= r2 && l2 <= r1) {                                  // If the total elements are even, then median is                  // the average of two middle elements                 if ((n + m) % 2 == 0)                     return (Math.Max(l1, l2) + Math.Min(r1, r2)) / 2.0;                  // If the total elements are odd, then median is                  // the middle element                 else                     return Math.Max(l1, l2);             }              // Check if we need to take lesser elements from arr1             if (l1 > r2)                 hi = mid1 - 1;              // Check if we need to take more elements from arr1             else                 lo = mid1 + 1;         }         return 0;     }      static void Main() {         int[] a = { 1, 12, 15, 26, 38 };         int[] b = { 2, 13, 17, 30, 45, 60 };          Console.WriteLine(medianOf2(a, b));     } } 
JavaScript
// JavaScript Program to find the median of two sorted arrays // of different size using Binary Search  function medianOf2(a, b) {     let n = a.length, m = b.length;      // If a[] has more elements, then call medianOf2      // with reversed parameters     if (n > m)         return medianOf2(b, a);      let lo = 0, hi = n;     while (lo <= hi) {         let mid1 = Math.floor((lo + hi) / 2);         let mid2 = Math.floor((n + m + 1) / 2) - mid1;          // Find elements to the left and right of partition in a[]         let l1 = (mid1 === 0) ? -Infinity : a[mid1 - 1];         let r1 = (mid1 === n) ? Infinity : a[mid1];          // Find elements to the left and right of partition in b[]         let l2 = (mid2 === 0) ? -Infinity : b[mid2 - 1];         let r2 = (mid2 === m) ? Infinity : b[mid2];          // If it is a valid partition         if (l1 <= r2 && l2 <= r1) {             // If the total elements are even, then median is              // the average of two middle elements             if ((n + m) % 2 === 0)                 return (Math.max(l1, l2) + Math.min(r1, r2)) / 2.0;              // If the total elements are odd, then median is              // the middle element             else                 return Math.max(l1, l2);         }          // Check if we need to take lesser elements from a[]         if (l1 > r2)             hi = mid1 - 1;          // Check if we need to take more elements from a[]         else             lo = mid1 + 1;     }     return 0; }  // Driver Code let a = [1, 12, 15, 26, 38]; let b = [2, 13, 17, 30, 45, 60];  console.log(medianOf2(a, b)); 

Output
17

Time Complexity: O(log(min(m, n))), since binary search is applied on the smaller array.
Auxiliary Space: O(1)



Next Article
Longest Increasing Subsequence Size (N log N)
author
kartik
Improve
Article Tags :
  • Divide and Conquer
  • DSA
  • Searching
  • Binary Search
  • median-finding
  • statistical-algorithms
Practice Tags :
  • Binary Search
  • Divide and Conquer
  • Searching

Similar Reads

  • Binary Search Algorithm - Iterative and Recursive Implementation
    Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Conditions to apply Binary Search Algorithm in a Data S
    15+ min read
  • What is Binary Search Algorithm?
    Binary Search is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half and the correct interval to find is decided based on the searched value and the mid value of the interval. Properties of Binary Search:Binary search is performed on the sorted data struct
    1 min read
  • Time and Space Complexity Analysis of Binary Search Algorithm
    Time complexity of Binary Search is O(log n), where n is the number of elements in the array. It divides the array in half at each step. Space complexity is O(1) as it uses a constant amount of extra space. AspectComplexityTime ComplexityO(log n)Space ComplexityO(1)The time and space complexities of
    3 min read
  • How to calculate "mid" or Middle Element Index in Binary Search?
    The most common method to calculate mid or middle element index in Binary Search Algorithm is to find the middle of the highest index and lowest index of the searchable space, using the formula mid = low + \frac{(high - low)}{2} Is this method to find mid always correct in Binary Search? Consider th
    6 min read
  • Variants of Binary Search

    • Variants of Binary Search
      Binary search is very easy right? Well, binary search can become complex when element duplication occurs in the sorted list of values. It's not always the "contains or not" we search using Binary Search, but there are 5 variants such as below:1) Contains (True or False) 2) Index of first occurrence
      15+ min read

    • Meta Binary Search | One-Sided Binary Search
      Meta binary search (also called one-sided binary search by Steven Skiena in The Algorithm Design Manual on page 134) is a modified form of binary search that incrementally constructs the index of the target value in the array. Like normal binary search, meta binary search takes O(log n) time. Meta B
      9 min read

    • The Ubiquitous Binary Search | Set 1
      We are aware of the binary search algorithm. Binary search is the easiest algorithm to get right. I present some interesting problems that I collected on binary search. There were some requests on binary search. I request you to honor the code, "I sincerely attempt to solve the problem and ensure th
      15+ min read

    • Uniform Binary Search
      Uniform Binary Search is an optimization of Binary Search algorithm when many searches are made on same array or many arrays of same size. In normal binary search, we do arithmetic operations to find the mid points. Here we precompute mid points and fills them in lookup table. The array look-up gene
      7 min read

    • Randomized Binary Search Algorithm
      We are given a sorted array A[] of n elements. We need to find if x is present in A or not.In binary search we always used middle element, here we will randomly pick one element in given range.In Binary Search we had middle = (start + end)/2 In Randomized binary search we do following Generate a ran
      13 min read

    • Abstraction of Binary Search
      What is the binary search algorithm? Binary Search Algorithm is used to find a certain value of x for which a certain defined function f(x) needs to be maximized or minimized. It is frequently used to search an element in a sorted sequence by repeatedly dividing the search interval into halves. Begi
      7 min read

    • N-Base modified Binary Search algorithm
      N-Base modified Binary Search is an algorithm based on number bases that can be used to find an element in a sorted array arr[]. This algorithm is an extension of Bitwise binary search and has a similar running time. Examples: Input: arr[] = {1, 4, 5, 8, 11, 15, 21, 45, 70, 100}, target = 45Output:
      10 min read

    Implementation of Binary Search in different languages

    • C Program for Binary Search
      In this article, we will understand the binary search algorithm and how to implement binary search programs in C. We will see both iterative and recursive approaches and how binary search can reduce the time complexity of the search operation as compared to linear search. Table of Content What is Bi
      7 min read

    • C++ Program For Binary Search
      Binary Search is a popular searching algorithm which is used for finding the position of any given element in a sorted array. It is a type of interval searching algorithm that keep dividing the number of elements to be search into half by considering only the part of the array where there is the pro
      5 min read

    • C Program for Binary Search
      In this article, we will understand the binary search algorithm and how to implement binary search programs in C. We will see both iterative and recursive approaches and how binary search can reduce the time complexity of the search operation as compared to linear search. Table of Content What is Bi
      7 min read

    • Binary Search functions in C++ STL (binary_search, lower_bound and upper_bound)
      In C++, STL provide various functions like std::binary_search(), std::lower_bound(), and std::upper_bound() which uses the the binary search algorithm for different purposes. These function will only work on the sorted data. There are the 3 binary search function in C++ STL: Table of Content binary_
      3 min read

    • Binary Search in Java
      Binary search is a highly efficient searching algorithm used when the input is sorted. It works by repeatedly dividing the search range in half, reducing the number of comparisons needed compared to a linear search. Here, we are focusing on finding the middle element that acts as a reference frame t
      7 min read

    • Binary Search (Recursive and Iterative) - Python
      Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Below is the step-by-step algorithm for Binary Search:
      6 min read

    • Binary Search In JavaScript
      Binary Search is a searching technique that works on the Divide and Conquer approach. It is used to search for any element in a sorted array. Compared with linear, binary search is much faster with a Time Complexity of O(logN), whereas linear search works in O(N) time complexity Examples: Input : ar
      3 min read

    • Binary Search using pthread
      Binary search is a popular method of searching in a sorted array or list. It simply divides the list into two halves and discards the half which has zero probability of having the key. On dividing, we check the midpoint for the key and use the lower half if the key is less than the midpoint and the
      8 min read

    Comparison with other Searching

    • Linear Search vs Binary Search
      Prerequisite: Linear SearchBinary SearchLINEAR SEARCH Assume that item is in an array in random order and we have to find an item. Then the only way to search for a target item is, to begin with, the first position and compare it to the target. If the item is at the same, we will return the position
      11 min read

    • Interpolation search vs Binary search
      Interpolation search works better than Binary Search for a Sorted and Uniformly Distributed array. Binary Search goes to the middle element to check irrespective of search-key. On the other hand, Interpolation Search may go to different locations according to search-key. If the value of the search-k
      7 min read

    • Why is Binary Search preferred over Ternary Search?
      The following is a simple recursive Binary Search function in C++ taken from here. C/C++ Code // CPP program for the above approach #include <bits/stdc++.h> using namespace std; // A recursive binary search function. It returns location of x in // given array arr[l..r] is present, otherwise -1
      11 min read

  • Binary Search Intuition and Predicate Functions
    The binary search algorithm is used in many coding problems, and it is usually not very obvious at first sight. However, there is certainly an intuition and specific conditions that may hint at using binary search. In this article, we try to develop an intuition for binary search. Introduction to Bi
    12 min read
  • Can Binary Search be applied in an Unsorted Array?
    Binary Search is a search algorithm that is specifically designed for searching in sorted data structures. This searching algorithm is much more efficient than Linear Search as they repeatedly target the center of the search structure and divide the search space in half. It has logarithmic time comp
    9 min read
  • Find a String in given Array of Strings using Binary Search
    Given a sorted array of Strings arr and a string x, The task is to find the index of x in the array using the Binary Search algorithm. If x is not present, return -1. Examples: Input: arr[] = {"contribute", "geeks", "ide", "practice"}, x = "ide"Output: 2Explanation: The String x is present at index
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences