Skip to content

Commit 36f27f5

Browse files
authored
Update median-of-two-sorted-arrays.cpp
updated solution using binary search
1 parent d3ba4d6 commit 36f27f5

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

median-of-two-sorted-arrays.cpp

+41
Original file line numberDiff line numberDiff line change
@@ -18,3 +18,44 @@ class Solution {
1818
return (n+m)%2?cur : double(last + cur)/2;
1919
}
2020
};
21+
22+
// updated solution using binary search
23+
24+
#include<bits/stdc++.h>
25+
using namespace std;
26+
27+
float median(int num 1[],int num2[],int m,int n) {
28+
if(m>n)
29+
return median(nums2,nums1,n,m);//ensuring that binary search happens on minimum size array
30+
31+
int low=0,high=m,medianPos=((m+n)+1)/2;
32+
while(low<=high) {
33+
int cut1 = (low+high)>>1;
34+
int cut2 = medianPos - cut1;
35+
36+
int l1 = (cut1 == 0)? INT_MIN:nums1[cut1-1];
37+
int l2 = (cut2 == 0)? INT_MIN:nums2[cut2-1];
38+
int r1 = (cut1 == m)? INT_MAX:nums1[cut1];
39+
int r2 = (cut2 == n)? INT_MAX:nums2[cut2];
40+
41+
if(l1<=r2 && l2<=r1) {
42+
if((m+n)%2 != 0)
43+
return max(l1,l2);
44+
else
45+
return (max(l1,l2)+min(r1,r2))/2.0;
46+
}
47+
else if(l1>r2) high = cut1-1;
48+
else low = cut1+1;
49+
}
50+
return 0.0;
51+
}
52+
53+
int main() {
54+
int nums1[] = {1,4,7,10,12};
55+
int nums2[] = {2,3,6,15};
56+
int m = sizeof(nums1)/sizeof(nums1[0]);
57+
int n = sizeof(nums2)/sizeof(nums2[0]);
58+
cout<<"The Median of two sorted arrays is"<<fixed<<setprecision(5)
59+
<<median(nums1,nums2,m,n);
60+
return 0;
61+
}

0 commit comments

Comments
 (0)