Author:龙箬
Computer Application Technology
Change the World with Data and Artificial Intelligence !
优快云@weixin_43975035
惟殷先人,有册有典
问题描述:
有两个数组A和B,假设A和B已经有序(从大到小),求A和B数组中所有数的第K大元素。
写出算法的基本思想
Procedure Kth_Elem (A, B, Aleft, Aright, Bleft, Bright, K)
if A.Length >= K and B.Length >= K and K is power of 2
// k为2的次幂,且A,B 的大小都大于k
if K == 1
if A[Aleft] > B[Bleft]
return B[Bleft]
else
return A[Aleft]
A_Kth = Aleft + K/2; B_Kth = Bleft + K/2;
if A[A_Kth] < B[B_Kth]
//A[k/2]之前数一定在A+B总的前k个数中,只需在A[k/2]之后数和B中查找第k/2大的数
return Kth_Elem (A, B, A_Kth+1, Aright, Bleft, Bright, K/2)
else
//B[k/2]之前数一定在A+B总的前k个数中,只需在B[k/2]之后数和A中查找第k/2大的数
return Kth_Elem (A, B, Aleft, Aright, B_Kth+1, Bright, K/2)
else if A.Length + B.Length > K
//如果A+B的数组大小大于k
A_Mid = (Aright- Aleft) /2; B_Mid = (Bright- Bleft) / 2;
Len_Half = A_Mid + B_Mid;
if Aleft > Aright
return B[Bleft+K-1]
if Bleft > Bright
return A[Aleft+K-1]
if A[A_Mid] < B[B_Mid]
if Len_Half > K
//表明第k大数存在于A和B的前一半中
return Kth_Elem (A, B, Aleft, Aright, Bleft, B_Mid-1, K)
else
//只需在A[A_Mid /2]之后的数和B中找第K- A_Mid大的数
return Kth_Elem (A, B, A_Mid+1 Aright, Bleft, Bright, K- A_Mid)
else
if Len_Half > K
//表明第k大数存在于A和B的前一半中
return Kth_Elem (A, B, Aleft, A_Mid-1, Bleft, Bright, K)
else
//只需在B[B_Mid /2]之后的数和A中找第K- M_Mid大的数
return Kth_Elem (A, B, Aleft Aright, B_Mid+1, Bright, K- B_Mid)
else if A.Length + B.Length == K
//如果A+B的数组大小等于k
if A[Aright] > B[Bright]
return A[Aright]
else
return B[Bright]
else
//找不到第K大数,返回0
return 0;
End Kth_Elem;
/*注:1)伪代码采用分治和递归的思想
2)相同颜色表示一个if-else代码段,黄色表示注释*/
参考致谢:
国科大 马丙鹏老师《计算机算法设计与分析》
如有侵权,请联系侵删
需要本实验源数据及代码的小伙伴请联系QQ:2225872659