算法设计技巧与分析p126习题6.27
*设A,B[1...n]是两个已排过序互不相同的整数组成的数组,给出一个有效的算法找出两个数组中2n个元素的中项
注意原来题目要求数组中元素各不相同,我们发现其实没有这个条件算法依旧可以运行,代码如下
public class MIDDATA {
public static Map<String,Integer> findMid(int[] a,int[] b,int lowa,int higha,int lowb,int highb,int len){
if(len==1){
Map map=new HashMap<String,Integer>();
map.put("mid1", a[lowa]);
map.put("mid2", b[lowb]);
return map;
}
else{
int mida=(lowa+higha)/2;
int midb=(lowb+highb)/2;
if(len%2==0){
if(a[mida]<b[midb]){
lowa=mida+1;
highb=midb;
len=len/2;
}
if(a[mida]>b[midb]){
higha=mida;
lowb=midb+1;
len=len/2;
}
if(a[mida]==b[midb]){
//如果长度是偶数那么恰好返回这两个中位数其中一个,以及中位数右侧与之靠的最近的一个数
Map map=new HashMap<String,Integer>();
map.put("mid1", a[mida]);
map.put("mid2", a[mida+1]<b[midb+1]? a[mida+1]:b[midb+1]);
return map;
}
return findMid(a,b,lowa,higha,lowb,highb,len);
}
else{
if(a[mida]<b[midb]){
lowa=mida;
highb=midb;
len=(len+1)/2;
}
if(a[mida]>b[midb]){
higha=mida;
lowb=midb;
len=(len+1)/2;
}
if(a[mida]==b[midb]){//如果长度是奇数那么恰好返回这两个中位数即可
Map map=new HashMap<String,Integer>();
map.put("mid1", a[mida]);
map.put("mid2", b[midb]);
return map;
}
return findMid(a,b,lowa,higha,lowb,highb,len);
}
}
}
public static void main(String args[]){
int[] a={2,7,9,14};
int[] b={3,7,13,21};
Map map=findMid(a,b,0,3,0,3,4);
System.out.print(map.get("mid1")+" "+map.get("mid2"));
}
}