Skip to content

Commit 1b42a48

Browse files
committed
Added comments for median of sorted arrays code
1 parent 491ca9b commit 1b42a48

1 file changed

Lines changed: 13 additions & 0 deletions

File tree

LeetCode/MedianOfTwoSortedArrays-BinarySearch.java

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,7 @@ public double findMedianSortedArrays(int[] nums1, int[] nums2)
7171
if(nums2.length < nums1.length)
7272
{
7373
return findMedianSortedArrays(nums2, nums1);
74+
//Considering partition length w.r.t. nums1
7475
}
7576
int n = nums1.length;
7677
int m = nums2.length;
@@ -83,14 +84,22 @@ public double findMedianSortedArrays(int[] nums1, int[] nums2)
8384
int partition1 = (low+high)>>1;
8485
int partition2 = (n+m+1)/2 - partition1;
8586

87+
//If the partition length becomes 0, we assign it large negative number(negative infinity)
88+
//left1 is the largest number from nums1 in left partition
8689
int left1 = (partition1==0)?Integer.MIN_VALUE : nums1[partition1-1];
90+
91+
//left2 is the largest number from nums2 in left partition
8792
int left2 = (partition2==0)?Integer.MIN_VALUE : nums2[partition2-1];
8893

94+
//right1 is the largest number from nums1 in right partition
8995
int right1 = (partition1==n)?Integer.MAX_VALUE : nums1[partition1];
96+
97+
//right2 is the largest number from nums2 in right partition
9098
int right2 = (partition2==m)?Integer.MAX_VALUE : nums2[partition2];
9199

92100
if(left1<=right2 && left2<=right1)
93101
{
102+
//If partition is valid
94103
if((n+m)%2==0)
95104
{
96105
return (max(left1, left2)+min(right1,right2))/2.0;
@@ -100,6 +109,7 @@ public double findMedianSortedArrays(int[] nums1, int[] nums2)
100109
return max(left1, left2);
101110
}
102111
}
112+
//else reduce the partition from nums1
103113
else if(left1 > right2)
104114
{
105115
high = partition1-1;
@@ -114,10 +124,13 @@ else if(left1 > right2)
114124

115125
}
116126

127+
//Utility function to return maximum of two numbers
117128
public int max(int a, int b)
118129
{
119130
return a>b? a:b;
120131
}
132+
133+
//Utility function to return minimun of two numbers
121134
public int min(int a, int b)
122135
{
123136
return a<b? a:b;

0 commit comments

Comments
 (0)