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, 6, 12, 15}, b[] = {-12, -10, -6, -3, 4, 10}
Output: The median is 3.
Explanation: The merged array is: ar3[] = {-12, -10, -6, -5 , -3, 3, 4, 6, 10, 12, 15}.
So the median of the merged array is 3
Input: a[] = {2, 3, 5, 8}, b[] = {10, 12, 14, 16, 18, 20}
Output: The median is 11.
Explanation : The merged array is: ar3[] = {2, 3, 5, 8, 10, 12, 14, 16, 18, 20}
If the number of the elements are even. So there are two middle elements.
Take the average between the two: (10 + 12) / 2 = 11.
Naive Approach to find Median of two sorted Arrays of different sizes
The idea is to merge them into third array and there are two cases:
- Case 1: If the length of the third array is odd, then the median is at (length)/2th index in the array obtained after merging both the arrays.
- Case 2: If the length of the third array is even, then the median will be the average of elements at index ((length)/2 ) and ((length)/2 – 1) in the array obtained after merging both arrays.
Illustration:
arr1[] = { -5, 3, 6, 12, 15 } , arr2[] = { -12, -10, -6, -3, 4, 10 }
- After merging them in a third array : arr3[] = { -5, 3, 6, 12, 15, -12, -10, -6, -3, 4, 10}
- Sort arr3[ ] = { -12, -10, -6, -5, -3, 3, 4, 6, 10, 12, 15 }
- As the length of arr3 is odd, so the median is 3
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int Solution( int arr[], int n)
{
if (n % 2 == 0) {
int z = n / 2;
int e = arr[z];
int q = arr[z - 1];
int ans = (e + q) / 2;
return ans;
}
else {
int z = round(n / 2);
return arr[z];
}
}
int main()
{
int arr1[] = { -5, 3, 6, 12, 15 };
int arr2[] = { -12, -10, -6, -3, 4, 10 };
int i = sizeof (arr1) / sizeof (arr1[0]);
int j = sizeof (arr2) / sizeof (arr2[0]);
int arr3[i + j];
int l = i + j;
for ( int k = 0; k < i; k++) {
arr3[k] = arr1[k];
}
int a = 0;
for ( int k = i; k < l; k++) {
arr3[k] = arr2[a++];
}
sort(arr3, arr3 + l);
cout << "Median = " << Solution(arr3, l);
}
|
Java
import java.io.*;
import java.util.Arrays;
public class GFG {
public static int Solution( int [] arr)
{
int n = arr.length;
if (n % 2 == 0 ) {
int z = n / 2 ;
int e = arr[z];
int q = arr[z - 1 ];
int ans = (e + q) / 2 ;
return ans;
}
else {
int z = Math.round(n / 2 );
return arr[z];
}
}
public static void main(String[] args)
{
int [] arr1 = { - 5 , 3 , 6 , 12 , 15 };
int [] arr2 = { - 12 , - 10 , - 6 , - 3 , 4 , 10 };
int i = arr1.length;
int j = arr2.length;
int [] arr3 = new int [i + j];
System.arraycopy(arr1, 0 , arr3, 0 , i);
System.arraycopy(arr2, 0 , arr3, i, j);
Arrays.sort(arr3);
System.out.print( "Median = " + Solution(arr3));
}
}
|
Python3
def Solution(arr):
n = len (arr)
if n % 2 = = 0 :
z = n / / 2
e = arr[z]
q = arr[z - 1 ]
ans = (e + q) / 2
return ans
else :
z = n / / 2
ans = arr[z]
return ans
if __name__ = = "__main__" :
arr1 = [ - 5 , 3 , 6 , 12 , 15 ]
arr2 = [ - 12 , - 10 , - 6 , - 3 , 4 , 10 ]
arr3 = arr1 + arr2
arr3.sort()
print ( "Median = " , Solution(arr3))
|
C#
using System;
using System.Collections.Generic;
public class GFG {
public static int Solution( int [] arr)
{
int n = arr.Length;
if (n % 2 == 0) {
int z = n / 2;
int e = arr[z];
int q = arr[z - 1];
int ans = (e + q) / 2;
return ans;
}
else {
int z = n / 2;
return arr[z];
}
}
static public void Main()
{
int [] arr1 = { -5, 3, 6, 12, 15 };
int [] arr2 = { -12, -10, -6, -3, 4, 10 };
var myList = new List< int >();
myList.AddRange(arr1);
myList.AddRange(arr2);
int [] arr3 = myList.ToArray();
Array.Sort(arr3);
Console.Write( "Median = " + Solution(arr3));
}
}
|
Javascript
function Solution(arr, n)
{
if (n % 2 == 0)
{
var z = n / 2;
var e = arr[z];
var q = arr[z - 1];
var ans = (e + q) / 2;
return ans;
}
else
{
var z = Math.floor(n / 2);
return arr[z];
}
}
var arr1 = [ -5, 3, 6, 12, 15 ];
var arr2 = [ -12, -10, -6, -3, 4, 10 ];
var i = arr1.length;
var j = arr2.length;
var l = i+j;
const arr3 = arr1.concat(arr2);
arr3.sort( function (a, b) {
return a - b;
});
console.log( "Median = " + Solution(arr3, l));
|
Time Complexity: O((N + M) * Log (N + M)), Time required to sort the array of size N + M
Auxiliary Space: O(N + M), Creating a new array of size N+M.
Median of two sorted arrays of different sizes by Merging Arrays efficiently:
The given arrays are sorted, so merge the sorted arrays in an efficient way and keep the count of elements inserted in the output array or printed form. So when the elements in the output array are half the original size of the given array print the element as a median element. There are two cases:
- Case 1: M+N is odd, the median is at (M+N)/2th index in the array obtained after merging both the arrays.
- Case 2: M+N is even, the median will be the average of elements at index ((M+N)/2 – 1) and (M+N)/2 in the array obtained after merging both the arrays
Illustration:
Given two array ar1[ ]= { 900 } and ar2[ ] = { 5, 8, 10, 20 } , n => Size of ar1 = 1 and m => Size of ar2 = 4
- Loop will run from 0 till 2.
- First iteration : { 900 } { 5, 8, 10, 20 } , m1 = 5
- Second iteration : { 900 } { 5, 8, 10, 20 }, m1 = 8
- Third iteration : { 900 } { 5, 8, 10, 20 }, m1 = 10
- As size of ar1 + ar2 = odd , hence we return m1 = 10 as the median
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int getMedian( int ar1[], int ar2[], int n, int m)
{
int i = 0;
int j = 0;
int count;
int m1 = -1, m2 = -1;
for (count = 0; count <= (m + n) / 2; count++) {
m2 = m1;
if (i != n && j != m) {
m1 = (ar1[i] > ar2[j]) ? ar2[j++] : ar1[i++];
}
else if (i < n) {
m1 = ar1[i++];
}
else {
m1 = ar2[j++];
}
}
if ((m + n) % 2 == 1) {
return m1;
}
else {
return (m1 + m2) / 2;
}
}
int main()
{
int ar1[] = { 900 };
int ar2[] = { 5, 8, 10, 20 };
int n1 = sizeof (ar1) / sizeof (ar1[0]);
int n2 = sizeof (ar2) / sizeof (ar2[0]);
cout << getMedian(ar1, ar2, n1, n2);
}
|
Java
import java.io.*;
class GFG {
static int getMedian( int ar1[], int ar2[], int n, int m)
{
int i = 0 ;
int j = 0 ;
int count;
int m1 = - 1 , m2 = - 1 ;
if ((m + n) % 2 == 1 ) {
for (count = 0 ; count <= (n + m) / 2 ; count++) {
if (i != n && j != m) {
m1 = (ar1[i] > ar2[j]) ? ar2[j++]
: ar1[i++];
}
else if (i < n) {
m1 = ar1[i++];
}
else {
m1 = ar2[j++];
}
}
return m1;
}
else {
for (count = 0 ; count <= (n + m) / 2 ; count++) {
m2 = m1;
if (i != n && j != m) {
m1 = (ar1[i] > ar2[j]) ? ar2[j++]
: ar1[i++];
}
else if (i < n) {
m1 = ar1[i++];
}
else {
m1 = ar2[j++];
}
}
return (m1 + m2) / 2 ;
}
}
public static void main(String[] args)
{
int ar1[] = { 900 };
int ar2[] = { 5 , 8 , 10 , 20 };
int n1 = ar1.length;
int n2 = ar2.length;
System.out.println(getMedian(ar1, ar2, n1, n2));
}
}
|
Python3
def getMedian(ar1, ar2, n, m):
i = 0
j = 0
m1, m2 = - 1 , - 1
for count in range (((n + m) / / 2 ) + 1 ):
if (i ! = n and j ! = m):
if ar1[i] > ar2[j]:
m1 = ar2[j]
j + = 1
else :
m1 = ar1[i]
i + = 1
elif (i < n):
m1 = ar1[i]
i + = 1
else :
m1 = ar2[j]
j + = 1
return m1 if (n + m) % 2 = = 1 else (m1 + m2) / / 2
ar1 = [ 900 ]
ar2 = [ 5 , 8 , 10 , 20 ]
n1 = len (ar1)
n2 = len (ar2)
print (getMedian(ar1, ar2, n1, n2))
|
C#
using System;
class GFG {
static int getMedian( int [] ar1, int [] ar2, int n, int m)
{
int i = 0;
int j = 0;
int count;
int m1 = -1, m2 = -1;
if ((m + n) % 2 == 1) {
for (count = 0; count <= (n + m) / 2; count++) {
if (i != n && j != m) {
m1 = (ar1[i] > ar2[j]) ? ar2[j++]
: ar1[i++];
}
else if (i < n) {
m1 = ar1[i++];
}
else {
m1 = ar2[j++];
}
}
return m1;
}
else {
for (count = 0; count <= (n + m) / 2; count++) {
m2 = m1;
if (i != n && j != m) {
m1 = (ar1[i] > ar2[j]) ? ar2[j++]
: ar1[i++];
}
else if (i < n) {
m1 = ar1[i++];
}
else {
m1 = ar2[j++];
}
}
return (m1 + m2) / 2;
}
}
public static void Main(String[] args)
{
int [] ar1 = { 900 };
int [] ar2 = { 5, 8, 10, 20 };
int n1 = ar1.Length;
int n2 = ar2.Length;
Console.WriteLine(getMedian(ar1, ar2, n1, n2));
}
}
|
Javascript
function getMedian(ar1, ar2, n, m)
{
let i = 0;
let j = 0;
let count;
let m1 = -1, m2 = -1;
if ((m + n) % 2 == 1)
{
for (count = 0;
count <= (n + m) / 2;
count++)
{
if (i != n && j != m)
{
m1 = (ar1[i] > ar2[j]) ?
ar2[j++] : ar1[i++];
}
else if (i < n)
{
m1 = ar1[i++];
}
else
{
m1 = ar2[j++];
}
}
return m1;
}
else
{
for (count = 0;
count <= (n + m) / 2;
count++)
{
m2 = m1;
if (i != n && j != m)
{
m1 = (ar1[i] > ar2[j]) ?
ar2[j++] : ar1[i++];
}
else if (i < n)
{
m1 = ar1[i++];
}
else
{
m1 = ar2[j++];
}
}
return (m1 + m2) / 2;
}
}
let ar1 = [900];
let ar2 = [5, 8, 10, 20];
let n1 = ar1.length;
let n2 = ar2.length;
console.log(getMedian(ar1, ar2, n1, n2));
|
Time Complexity: O(M + N). To merge both arrays O(M+N) time is needed.
Auxiliary Space: O(1). No extra space is required.
The given two arrays are sorted, so we can utilize the ability of Binary Search to divide the array and find the median.
Median means the point at which the whole array is divided into two parts. Hence since the two arrays are not merged so to get the median we require merging which is costly.
Hence instead of merging, we will use a modified binary search algorithm to efficiently find the median.
Below is the implementation:
C++
#include <bits/stdc++.h>
using namespace std;
double Median(vector< int >& A, vector< int >& B)
{
int n = A.size();
int m = B.size();
if (n > m)
return Median(B, A);
int start = 0;
int end = n;
int realmidinmergedarray = (n + m + 1) / 2;
while (start <= end) {
int mid = (start + end) / 2;
int leftAsize = mid;
int leftBsize = realmidinmergedarray - mid;
int leftA
= (leftAsize > 0)
? A[leftAsize - 1]
: INT_MIN;
int leftB
= (leftBsize > 0) ? B[leftBsize - 1] : INT_MIN;
int rightA
= (leftAsize < n) ? A[leftAsize] : INT_MAX;
int rightB
= (leftBsize < m) ? B[leftBsize] : INT_MAX;
if (leftA <= rightB and leftB <= rightA) {
if ((m + n) % 2 == 0)
return (max(leftA, leftB)
+ min(rightA, rightB))
/ 2.0;
return max(leftA, leftB);
}
else if (leftA > rightB) {
end = mid - 1;
}
else
start = mid + 1;
}
return 0.0;
}
int main()
{
vector< int > arr1 = { -5, 3, 6, 12, 15 };
vector< int > arr2 = { -12, -10, -6, -3, 4, 10 };
cout << "Median of the two arrays are" << endl;
cout << Median(arr1, arr2);
return 0;
}
|
Java
public class GFG {
static double Median( int [] A, int [] B)
{
int n = A.length;
int m = B.length;
if (n > m)
return Median(B,
A);
int start = 0 ;
int end = n;
int realmidinmergedarray = (n + m + 1 ) / 2 ;
while (start <= end) {
int mid = (start + end) / 2 ;
int leftAsize = mid;
int leftBsize = realmidinmergedarray - mid;
int leftA
= (leftAsize > 0 )
? A[leftAsize - 1 ]
: Integer
.MIN_VALUE;
int leftB = (leftBsize > 0 ) ? B[leftBsize - 1 ]
: Integer.MIN_VALUE;
int rightA = (leftAsize < n)
? A[leftAsize]
: Integer.MAX_VALUE;
int rightB = (leftBsize < m)
? B[leftBsize]
: Integer.MAX_VALUE;
if (leftA <= rightB && leftB <= rightA) {
if ((m + n) % 2 == 0 )
return (Math.max(leftA, leftB)
+ Math.min(rightA, rightB))
/ 2.0 ;
return Math.max(leftA, leftB);
}
else if (leftA > rightB) {
end = mid - 1 ;
}
else
start = mid + 1 ;
}
return 0.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( "Median of the two arrays are" );
System.out.println(Median(arr1, arr2));
}
}
|
Python3
class Solution:
def Median( self , A, B):
n = len (A)
m = len (B)
if (n > m):
return self .Median(B, A)
start = 0
end = n
realmidinmergedarray = (n + m + 1 ) / / 2
while (start < = end):
mid = (start + end) / / 2
leftAsize = mid
leftBsize = realmidinmergedarray - mid
leftA = A[leftAsize - 1 ] if (leftAsize > 0 ) else float ( '-inf' )
leftB = B[leftBsize - 1 ] if (leftBsize > 0 ) else float ( '-inf' )
rightA = A[leftAsize] if (leftAsize < n) else float ( 'inf' )
rightB = B[leftBsize] if (leftBsize < m) else float ( 'inf' )
if leftA < = rightB and leftB < = rightA:
if ((m + n) % 2 = = 0 ):
return ( max (leftA, leftB) + min (rightA, rightB)) / 2.0
return max (leftA, leftB)
elif (leftA > rightB):
end = mid - 1
else :
start = mid + 1
ans = Solution()
arr1 = [ - 5 , 3 , 6 , 12 , 15 ]
arr2 = [ - 12 , - 10 , - 6 , - 3 , 4 , 10 ]
print ( "Median of the two arrays is" )
print (ans.Median(arr1, arr2))
|
C#
using System;
public class GFG {
static double Median( int [] A, int [] B)
{
int n = A.Length;
int m = B.Length;
if (n > m)
return Median(B,
A);
int start = 0;
int end = n;
int realmidinmergedarray = (n + m + 1) / 2;
while (start <= end) {
int mid = (start + end) / 2;
int leftAsize = mid;
int leftBsize = realmidinmergedarray - mid;
int leftA
= (leftAsize > 0)
? A[leftAsize - 1]
: Int32.MinValue;
int leftB = (leftBsize > 0) ? B[leftBsize - 1]
: Int32.MinValue;
int rightA = (leftAsize < n) ? A[leftAsize]
: Int32.MaxValue;
int rightB = (leftBsize < m) ? B[leftBsize]
: Int32.MaxValue;
if (leftA <= rightB && leftB <= rightA) {
if ((m + n) % 2 == 0)
return (Math.Max(leftA, leftB)
+ Math.Min(rightA, rightB))
/ 2.0;
return Math.Max(leftA, leftB);
}
else if (leftA > rightB) {
end = mid - 1;
}
else
start = mid + 1;
}
return 0.0;
}
public static void Main()
{
int [] arr1 = { -5, 3, 6, 12, 15 };
int [] arr2 = { -12, -10, -6, -3, 4, 10 };
Console.WriteLine( "Median of the two arrays are" );
Console.WriteLine(Median(arr1, arr2));
}
}
|
Javascript
<script>
function Median(A, B) {
let n = A.length;
let m = B.length;
if (n > m)
return Median(B, A);
let start = 0;
let end = n;
let realmidinmergedarray = Math.floor((n + m + 1) / 2);
while (start <= end) {
let mid = Math.floor((start + end) / 2);
let leftAsize = mid;
let leftBsize = realmidinmergedarray - mid;
let leftA
= (leftAsize > 0)
? A[leftAsize - 1]
: Number.MIN_VALUE;
let leftB
= (leftBsize > 0) ? B[leftBsize - 1] : INT_MIN;
let rightA
= (leftAsize < n) ? A[leftAsize] : INT_MAX;
let rightB
= (leftBsize < m) ? B[leftBsize] : INT_MAX;
if (leftA <= rightB && leftB <= rightA) {
if ((m + n) % 2 == 0)
return Math.floor((Math.max(leftA, leftB)
+ Math.min(rightA, rightB))
/ 2.0);
return Math.max(leftA, leftB);
}
else if (leftA > rightB) {
end = mid - 1;
}
else
start = mid + 1;
}
return 0.0;
}
let arr1 = [-5, 3, 6, 12, 15];
let arr2 = [-12, -10, -6, -3, 4, 10];
document.write( "Median of the two arrays are" + "<br>" );
document.write(Median(arr1, arr2))
</script>
|
Output
Median of the two arrays are
3
Time Complexity: O(min(log M, log N)): Since binary search is being applied on the smaller of the 2 arrays
Auxiliary Space: O(1)
Median of two sorted arrays of different sizes using Priority Queue:
In this Approach we have used Priority Queue (min Heap) to find out the median.
The Idea is simple, just push the elements into a single Priority Queue from both arrays. Now we have to find median from priority queue by performing a simple traversal through it upto median.
Illustration:
A[ ] = {-2, 3, 4, 5}, N = 4 & B[ ] = {-4, -1, 7, 8, 9}, M = 5
Step 1: Adding elements to priority queue(pq) from array A
- pq.push(-2)
- pq.push(3)
- pq.push(4)
- pq.push(5)
After adding array A elements to priority queue it will look as pq = {-2, 3, 4, 5}
Step 2: Adding elements to priority queue(pq) from array B
- pq.push(-4)
- pq.push(-1)
- pq.push(7)
- pq.push(8)
- pq.push(9)
After adding array B elements to priority queue it will look as pq = {-4, -2, -1, 3, 4, 5, 7, 8, 9}
Step 3: Now we have to find median from Priority Queue based on following conditions:
- if N+M is odd
- then traverse priority queue upto (n+m)/2 by popping element by element
- Then display median as pq.top()
- if N+M is even
- then traverse priority queue upto (n+m)/2 && ((n+m)/2)-1
- Then median = average of both top values of priority queue
In this case the median is 4
Below is the implementation of the above problem:
C++
#include <bits/stdc++.h>
using namespace std;
double Median(vector< int >& A, vector< int >& B)
{
int i;
int n = A.size();
int m = B.size();
priority_queue< int , vector< int >, greater< int > > pq;
for (i = 0; i < n; i++)
pq.push(A[i]);
for (i = 0; i < m; i++)
pq.push(B[i]);
int check = n + m;
double count = -1;
double mid1, mid2;
while (!pq.empty()) {
count++;
if (check % 2 != 0 && count == check / 2) {
double ans = pq.top();
return ans;
}
if (check % 2 == 0 && count == (check / 2) - 1)
mid1 = pq.top();
if (check % 2 == 0 && count == check / 2) {
mid2 = pq.top();
double ans = (mid1 + mid2) / 2;
return ans;
}
pq.pop();
}
return 0.00000;
}
int main()
{
vector< int > arr1 = { -2, 3, 4, 5 };
vector< int > arr2 = { -4, -1, 7, 8, 9 };
cout << "Median of the two arrays are" << endl;
cout << Median(arr1, arr2);
return 0;
}
|
Java
import java.util.PriorityQueue;
import java.util.Scanner;
import java.util.Vector;
public class Main {
public static double Median(Vector<Integer> A,
Vector<Integer> B)
{
int i;
int n = A.size();
int m = B.size();
PriorityQueue<Integer> pq
= new PriorityQueue<Integer>();
for (i = 0 ; i < n; i++) {
pq.add(A.get(i));
}
for (i = 0 ; i < m; i++) {
pq.add(B.get(i));
}
int check = n + m;
double count = - 1 ;
double mid1 = - 1 , mid2 = - 1 ;
while (!pq.isEmpty()) {
count++;
if (check % 2 != 0 && count == check / 2 ) {
double ans = pq.peek();
return ans;
}
if (check % 2 == 0
&& count == (check / 2 ) - 1 ) {
mid1 = pq.peek();
}
if (check % 2 == 0 && count == check / 2 ) {
mid2 = pq.peek();
double ans = (mid1 + mid2) / 2 ;
return ans;
}
pq.poll();
}
return 0.00000 ;
}
public static void main(String[] args)
{
Vector<Integer> arr1 = new Vector<Integer>();
arr1.add(- 2 );
arr1.add( 3 );
arr1.add( 4 );
arr1.add( 5 );
Vector<Integer> arr2 = new Vector<Integer>();
arr2.add(- 4 );
arr2.add(- 1 );
arr2.add( 7 );
arr2.add( 8 );
arr2.add( 9 );
System.out.println( "Median of the two arrays are" );
System.out.println(Median(arr1, arr2));
}
}
|
Python3
import heapq
def Median(A, B):
n, m = len (A), len (B)
pq = []
for i in range (n):
heapq.heappush(pq, A[i])
for i in range (m):
heapq.heappush(pq, B[i])
check = n + m
count = - 1
mid1, mid2 = - 1 , - 1
while pq:
count + = 1
if check % 2 ! = 0 and count = = check / / 2 :
return pq[ 0 ]
if check % 2 = = 0 and count = = (check / / 2 ) - 1 :
mid1 = pq[ 0 ]
if check % 2 = = 0 and count = = check / / 2 :
mid2 = heapq.heappop(pq)
return (mid1 + mid2) / 2
heapq.heappop(pq)
return 0.00000
arr1 = [ - 2 , 3 , 4 , 5 ]
arr2 = [ - 4 , - 1 , 7 , 8 , 9 ]
print ( "Median of the two arrays are" )
print (Median(arr1, arr2))
|
C#
using System;
using System.Collections.Generic;
namespace MedianOfTwoSortedArrays {
class Program {
static double Median(List< int > A, List< int > B)
{
int n = A.Count;
int m = B.Count;
int i;
var pq = new SortedSet< int >();
for (i = 0; i < n; i++)
pq.Add(A[i]);
for (i = 0; i < m; i++)
pq.Add(B[i]);
int check = n + m;
double count = -1;
double mid1, mid2;
while (pq.Count != 0) {
count++;
if (check % 2 != 0 && count == check / 2) {
double ans = pq.Min;
return ans;
}
if (check % 2 == 0
&& count == (check / 2) - 1) {
mid1 = pq.Min;
if (check % 2 == 0 && count == check / 2) {
mid2 = pq.Min;
double ans = (mid1 + mid2) / 2;
return ans;
}
}
pq.Remove(pq.Min);
}
return 0.00000;
}
static void Main( string [] args)
{
List< int > arr1 = new List< int >{ -2, 3, 4, 5 };
List< int > arr2 = new List< int >{ -4, -1, 7, 8, 9 };
Console.WriteLine( "Median of the two arrays are" );
Console.WriteLine(Median(arr1, arr2));
Console.ReadLine();
}
}
}
|
Javascript
function Median(A, B) {
let n = A.length;
let m = B.length;
let pq = new PriorityQueue();
for (let i = 0; i < n; i++) {
pq.push(A[i]);
}
for (let i = 0; i < m; i++) {
pq.push(B[i]);
}
let check = n + m;
let count = -1;
let mid1, mid2;
while (!pq.isEmpty()) {
count++;
if (check % 2 !== 0 && count === Math.floor(check / 2)) {
let ans = pq.top();
return ans;
}
if (check % 2 === 0 && count === (check / 2) - 1) {
mid1 = pq.top();
}
if (check % 2 === 0 && count === check / 2) {
mid2 = pq.top();
let ans = (mid1 + mid2) / 2;
return ans;
}
pq.pop();
}
return 0.00000;
}
class PriorityQueue {
constructor() {
this .data = [];
}
push(value) {
this .data.push(value);
this .bubbleUp( this .data.length - 1);
}
pop() {
let result = this .data[0];
let end = this .data.pop();
if ( this .data.length > 0) {
this .data[0] = end;
this .bubbleDown(0);
}
return result;
}
top() {
return this .data[0];
}
isEmpty() {
return this .data.length === 0;
}
bubbleUp(index) {
let parent = Math.floor((index + 1) / 2) - 1;
if (parent >= 0 && this .data[parent] > this .data[index]) {
[ this .data[parent], this .data[index]] = [ this .data[index], this .data[parent]];
this .bubbleUp(parent);
}
}
bubbleDown(index) {
let child1 = (index + 1) * 2 - 1;
let child2 = (index + 1) * 2;
let minIndex = index;
if (child1 < this .data.length && this .data[child1] < this .data[minIndex]) {
minIndex = child1;
}
if (child2 < this .data.length && this .data[child2] < this .data[minIndex]) {
minIndex = child2;
}
if (minIndex !== index) {
[ this .data[index], this .data[minIndex]] = [ this .data[minIndex], this .data[index]];
this .bubbleDown(minIndex);
}
}
}
let arr1 = [-2, 3, 4, 5];
let arr2 = [-4, -1, 7, 8, 9];
console.log( "Median of the two arrays are" );
console.log(Median(arr1, arr2));
|
Output
Median of the two arrays are
4
Time Complexity: O(max(N, M)*log(max(N, M))): Since the priority queue is implemented from two arrays
Auxiliary Space: O(N+M): for storing two array values in the priority queue.
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!