Skip to content

Commit

Permalink
Merge pull request #136 from soumenmanik1911/patch-1
Browse files Browse the repository at this point in the history
Efficiently find the median of two sorted arrays without fully merging them in java
  • Loading branch information
Ayu-hack authored Oct 8, 2024
2 parents 86be35f + f3f2981 commit da64c47
Showing 1 changed file with 55 additions and 0 deletions.
55 changes: 55 additions & 0 deletions Java/MedianOfTwoSortedArrays.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
public class MedianOfTwoSortedArrays {

public static double findMedianSortedArrays(int[] nums1, int[] nums2) {
// Ensure nums1 is the smaller array
if (nums1.length > nums2.length) {
int[] temp = nums1;
nums1 = nums2;
nums2 = temp;
}

int x = nums1.length;
int y = nums2.length;
int low = 0, high = x;

while (low <= high) {
int partitionX = (low + high) / 2;
int partitionY = (x + y + 1) / 2 - partitionX;


int maxLeftX = (partitionX == 0) ? Integer.MIN_VALUE : nums1[partitionX - 1];
int minRightX = (partitionX == x) ? Integer.MAX_VALUE : nums1[partitionX];

int maxLeftY = (partitionY == 0) ? Integer.MIN_VALUE : nums2[partitionY - 1];
int minRightY = (partitionY == y) ? Integer.MAX_VALUE : nums2[partitionY];

if (maxLeftX <= minRightY && maxLeftY <= minRightX) {

if ((x + y) % 2 == 0) {
return (Math.max(maxLeftX, maxLeftY) + Math.min(minRightX, minRightY)) / 2.0;
} else {
return Math.max(maxLeftX, maxLeftY);
}
} else if (maxLeftX > minRightY) {

high = partitionX - 1;
} else {

low = partitionX + 1;
}
}


throw new IllegalArgumentException("Input arrays are not sorted");
}

public static void main(String[] args) {
int[] nums1 = {1, 3};
int[] nums2 = {2};
System.out.println("Median is: " + findMedianSortedArrays(nums1, nums2)); // Output: 2.0

int[] nums3 = {1, 2};
int[] nums4 = {3, 4};
System.out.println("Median is: " + findMedianSortedArrays(nums3, nums4)); // Output: 2.5
}
}

0 comments on commit da64c47

Please sign in to comment.