设X[0:n - 1 ] 和 Y[0:n - 1 ] 为两个数组,每个数组含有 n 个已经 排好序的数,试设计一个O(log n ) 时间的算法,找出X 和 Y 的 2n个数的中位数
public class Median_of_two_sorted_arrays {//
public static void main(String args[]){
// int []arr1 = {1,4,7,9};
// int []arr2 = {2,3,5,6};
int []arr1 = {1,4,6,8,11};
int []arr2 = {2,3,5,7,9};
// int []arr1 = {1,2,3,4,5};
// int []arr2 = {6,7,8,9,10};
// int []arr1 = new int[4];
// int []arr2 = new int[4];
// Scanner scanner = new Scanner(System.in);
// for(int i = 0;i < 4;i++){
// arr1[i] = scanner.nextInt();
// }
// for(int i = 0;i < 4;i++){
// arr2[i] = scanner.nextInt();
// }
System.out.println("利用分治法求两个有序数组的中位数为:" + findMedianSortedArrays(arr1,arr2));
}
public static double findMedianSortedArrays(int []arr1,int []arr2){
int n = arr1.length;
int m = arr2.length;
int L1 = 0,L2 = 0,R1 = 0,R2 = 0,c1,c2,left = 0,right = n - 1;
c1 = (left + right) / 2;
while (left <= right){
c2 = n - c1;
L1 = (c1 == 0)?arr1[0]:arr1[c1 - 1];//考虑一方数组完全大于另一数组情况
R1 = (c1 == n - 1)?arr1[n - 1]:arr1[c1];
L2 = (c2 == 0)?arr2[0]:arr2[c2 - 1];
R2 = (c2 == n - 1)?arr2[n - 1]:arr2[c2];
if(c1 == 0){//当arr1完全大于arr2的情况
return (double)(R2 + L1) /2;
}
else if(c1 == n - 1) {//当arr1完全小于arr2的情况
return (double)(L2 + R1) /2;
}
if(L1 > R2){
c1--;
}
else if(L2 > R1){
c1++;
}
else {
break;
}
}
return ((double)(max(L1,L2)) + min(R1,R2)) / 2;
}
public static int max(int a,int b){
return a > b?a:b;
}
public static int min(int a,int b){
return a < b?a:b;
}
}