Median of 2 Sorted Arrays of Equal Size
Understanding the Problem
The goal is to find the median of two sorted arrays of equal size.
Method 1: Simple Merge
This method merges the two arrays and finds the median.
public class MedianOfSortedArrays {
public static double findMedianSortedArrays(int[] arr1, int[] arr2) {
int n = arr1.length;
int[] merged = new int[2 * n];
int i = 0, j = 0, k = 0;
while (i < n && j < n) {
if (arr1[i] < arr2[j]) {
merged[k++] = arr1[i++];
} else {
merged[k++] = arr2[j++];
}
}
while (i < n) merged[k++] = arr1[i++];
while (j < n) merged[k++] = arr2[j++];
return (merged[n - 1] + merged[n]) / 2.0;
}
public static void main(String[] args) {
int[] arr1 = {1, 3};
int[] arr2 = {2, 4};
System.out.println("Median: " + findMedianSortedArrays(arr1, arr2));
}
}
Output:
Median: 2.5
Method 2: Binary Search
This method uses binary search to find the median efficiently.
public class MedianOfSortedArrays {
public static double findMedianSortedArrays(int[] arr1, int[] arr2) {
int n = arr1.length;
int low = 0, high = n;
while (low <= high) {
int partition1 = (low + high) / 2;
int partition2 = n - partition1;
int maxLeft1 = (partition1 == 0) ? Integer.MIN_VALUE : arr1[partition1 - 1];
int minRight1 = (partition1 == n) ? Integer.MAX_VALUE : arr1[partition1];
int maxLeft2 = (partition2 == 0) ? Integer.MIN_VALUE : arr2[partition2 - 1];
int minRight2 = (partition2 == n) ? Integer.MAX_VALUE : arr2[partition2];
if (maxLeft1 <= minRight2 && maxLeft2 <= minRight1) {
return (Math.max(maxLeft1, maxLeft2) + Math.min(minRight1, minRight2)) / 2.0;
} else if (maxLeft1 > minRight2) {
high = partition1 - 1;
} else {
low = partition1 + 1;
}
}
throw new IllegalArgumentException("Input arrays are not sorted.");
}
public static void main(String[] args) {
int[] arr1 = {1, 3};
int[] arr2 = {2, 4};
System.out.println("Median: " + findMedianSortedArrays(arr1, arr2));
}
}
Output:
Median: 2.5
Method 3: Using a Combined Array
This method combines the arrays and finds the median directly.
import java.util.Arrays;
public class MedianOfSortedArrays {
public static double findMedianSortedArrays(int[] arr1, int[] arr2) {
int n = arr1.length;
int[] combined = new int[2 * n];
System.arraycopy(arr1, 0, combined, 0, n);
System.arraycopy(arr2, 0, combined, n, n);
Arrays.sort(combined);
return (combined[n - 1] + combined[n]) / 2.0;
}
public static void main(String[] args) {
int[] arr1 = {1, 3};
int[] arr2 = {2, 4};
System.out.println("Median: " + findMedianSortedArrays(arr1, arr2));
}
}
Output:
Median: 2.5