为什么要分区排序数组以查找中位数

时间:2013-10-09 06:24:12

标签: algorithm list median

我在网上找到了一个例子,用于查找2个排序数组的中位数。但是我很难理解为什么每次如果它已经排序就需要对它进行分区。此外,如果它没有找到2个相等的中位数会发生什么?

希望得到一些澄清。感谢

http://www-scf.usc.edu/~csci303/cs303hw3solutions.pdf

Problem 3 (9.3-8):
Let X[1, . . . , n] and Y [1, . . . , n] be two arrays, each containing n numbers already in sorted order. Give an O(lg n)-time algorithm to find the median of all 2n elements in arrays X and Y .
Solution 3:

Two-List-Median(X, p, q, Y, s, t)
mx ← Index-Of-Median(X, p, q)
my ← Index-Of-Median(Y, s, t)
X[mx] ↔ X[q]
Y [my] ↔ Y [t] 
Partition(X, p, q)
Partition(Y, s, t) 
if X[mx] = Y [my]
return X[mx]
else if X[mx] > Y [my]
return Two-List-Median(X, p, mx − 1, Y, my + 1, t)
else
return Two-List-Median(X, mx + 1, q, Y, s, my − 1)

0 个答案:

没有答案