# （算法）两个有序数组的第k大的数

## 思路：

1、如果k为2的次幂，且A,B 的大小都大于k，那么

2、如果A+B的数组大小大于k

## 代码：

```#include<iostream>

using namespace std;

// if length of A && length of B >=k
// k is power of 2
int FindKthElem_1(int A[],int aLeft,int aRight,int B[],int bLeft,int bRight,int k){
/*
if(aLeft>aRight)
return B[bLeft+k-1];
if(bLeft>bRight)
return A[aLeft+k-1];
*/
if(k==1){
if(A[aLeft]>B[bLeft])
return B[bLeft];
else
return A[aLeft];
}

int aKth=aLeft+(k>>1)-1;
int bKth=bLeft+(k>>1)-1;

if(A[aKth]<B[bKth])
return FindKthElem_1(A,aKth+1,aRight,B,bLeft,bRight,(k>>1));
else
return FindKthElem_1(A,aLeft,aRight,B,bKth+1,bRight,(k>>1));
}

// if length of A + length of B >=k
int FindKthElem_2(int A[],int aLeft,int aRight,int B[],int bLeft,int bRight,int k){
if(aLeft>aRight)
return B[bLeft+k-1];
if(bLeft>bRight)
return A[aLeft+k-1];

int aMid=aLeft+((aRight-aLeft)>>1);
int bMid=bLeft+((bRight-bLeft)>>1);

int halfLen=aMid-aLeft+bMid-bLeft+2;

if(A[aMid]<B[bMid]){
if(halfLen>k){
return FindKthElem_2(A,aLeft,aRight,B,bLeft,bMid-1,k);
}
else{
return FindKthElem_2(A,aMid+1,aRight,B,bLeft,bRight,k-(aMid-aLeft+1));
}
}
else{
if(halfLen>k){
return FindKthElem_2(A,aLeft,aMid-1,B,bLeft,bRight,k);
}
else{
return FindKthElem_2(A,aLeft,aRight,B,bMid+1,bRight,k-(bMid-bLeft+1));
}
}
}

int main(){
int A[]={1,2,3,7,8,9};
int B[]={4,5,6,10,11,12};

int aLen=sizeof(A)/sizeof(A[0]);
int bLen=sizeof(B)/sizeof(B[0]);

int k;
while(true){