-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmedian.java
More file actions
58 lines (55 loc) · 1.55 KB
/
median.java
File metadata and controls
58 lines (55 loc) · 1.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import java.util.Scanner;
import static java.lang.Math.max;
import static java.lang.Math.min;
public class median {
static double calc_median(int a[],int b[]){
int n1=a.length;
int n2=b.length;
int n=n1+n2;
if(n1>n2){
return calc_median(b,a);
}
int low=0;
int high=n1;
int left=(n1+n2+1)/2;
while(low<=high){
int mid1=(low+high)>>1;
int mid2=left-mid1;
int l1=Integer.MIN_VALUE,l2=Integer.MIN_VALUE;
int r1=Integer.MAX_VALUE,r2=Integer.MAX_VALUE;
if(mid1<n1){
r1=a[mid1];
}
if(mid2<n2){
r2=b[mid2];
}
if(mid1-1>=0){
l1=a[mid1-1];
}
if(mid2-1>=0){
l2=b[mid2-1];
}
if(l1<=r2 && l2<=r1){
if(n%2==1){
return Math.max(l1,l2);
}
else{
return ((double)(Math.max(l1,l2)+Math.min(r1,r2)))/2.0;
}
}
else if(l1>=r2){
high=mid1-1;
}
else{
low=mid1+1;
}
}
return 0;
}
public static void main(String[] args) {
int arr1[]={7,12,14,15};
int arr2[]={1,2,3,4,9,11};
double Median=calc_median(arr1, arr2);
System.out.println("The median of the final sorted array is "+Median);
}
}