Median of two sorted array GFG *******

 package com.company;


import java.util.Arrays;

public class MedianOfSortedArray {
//Median of two sorted array
public static double median(int[] arr, int[] array) {
int n = arr.length;
int m = array.length;
int[] find = new int[n + m];

for (int i = 0; i < n; i++) {
find[i] = arr[i];
}

for (int i = 0; i < m; i++) {
find[i + n] = array[i];
}

Arrays.sort(find);
int a = find.length;

if (a % 2 == 0) {
int sum = find[a / 2] + find[a / 2 - 1];
return sum / 2.0;
} else
return find[a / 2];
}
//Efficient solution
public static double getMedian(int[] arr1, int[] arr2) {
int n1 = arr1.length;
int n2 = arr2.length;

int low = 0;
int high = n1;
while(low <= high){
int i1 = (low + high) / 2;
int i2 = (n1 + n2 + 1 ) / 2 - i1;
int min1 = (i1 == n1)?Integer.MAX_VALUE:arr1[i1];
int min2 = (i2 == n2)?Integer.MAX_VALUE:arr2[i2];
int max1 = (i1 == 0)?Integer.MIN_VALUE:arr1[i1 - 1];
int max2 = (i2 == 0)?Integer.MIN_VALUE:arr2[i2 - 1];
if(max1 <= min2 && max2 <= min1) {
if(n1 + n2 % 2 == 0) {
return (double)(Math.max(max1, max2) + Math.min(min1, min2)) / 2;
}
else{
return (double)Math.max(max1,max2);
}
}
else if(max2 > min1){
low = i1 + 1;
}
else{
high = i1 - 1;
}
}
return -1;
}
public static void main(String[] args) {
int[] test = {30,40,50,60};
int[] test2 = {5,6,7,8,9};
System.out.println(getMedian(test, test2));
}
}

Comments