Open In App

C / C++ Program for Median of two sorted arrays of same size

Improve
Improve
Like Article
Like
Save
Share
Report

Write a C/C++ program for a given 2 sorted arrays A and B of size n each. the task is to find the median of the array obtained by merging the above 2 arrays(i.e. array of length 2n). The complexity should be O(log(n)).

Examples:

Input: ar1[] = {1, 12, 15, 26, 38}
ar2[] = {2, 13, 17, 30, 45}
Output: 16
Explanation:
After merging two arrays, we get {1, 2, 12, 13, 15, 17, 26, 30, 38, 45}
The middle two elements are 15 and 17
The average of middle elements is (15 + 17)/2 which is equal to 16

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

C/C++ Program for Median of two sorted arrays of same size using Simply count while Merging:

Use 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.

Below is the implementation of the above approach:

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


Output

Median is 16

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

C/C++ Program for Median of two sorted arrays of same size (By comparing the medians of two arrays):

Step-by-step approach:

  • Merge the two input arrays ar1[] and ar2[].
  • Sort ar1[] and ar2[] respectively.
  • 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


Output

Median is 16

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

C/C++ Program for Median of two sorted arrays of same size using Binary Search:

Step-by-step approach:

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
  • Median of two sorted arrays of same size

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


Output

Median is 4.5

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

Please refer complete article on Median of two sorted arrays of same size for more details!



Last Updated : 24 Oct, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads