-
Notifications
You must be signed in to change notification settings - Fork 466
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #136 from soumenmanik1911/patch-1
Efficiently find the median of two sorted arrays without fully merging them in java
- Loading branch information
Showing
1 changed file
with
55 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} | ||
} |