【发布时间】:2018-01-16 21:01:57
【问题描述】:
我一直试图理解为什么以下算法无效。
1) Calculate the medians m1 and m2 of the input arrays ar1[]
and ar2[] respectively.
2) If m1 and m2 both are equal then we are done.
return m1 (or m2)
3) If m1 is greater than m2, then median is present in one
of the below two subarrays.
a) From first element of ar1 to m1 (ar1[0...|_n/2_|])
b) From m2 to last element of ar2 (ar2[|_n/2_|...n-1])
4) If m2 is greater than m1, then median is present in one
of the below two subarrays.
a) From m1 to last element of ar1 (ar1[|_n/2_|...n-1])
b) From first element of ar2 to m2 (ar2[0...|_n/2_|])
5) Repeat the above process until size of both the subarrays
becomes 2.
6) If size of the two arrays is 2 then use below formula to get
the median.
Median = (max(ar1[0], ar2[0]) + min(ar1[1], ar2[1]))/2
我的难点在于算法的核心步骤 3 和 4。这是我的想法:
如果 m1 > m2 那么 m1 大于合并数组中元素的一半,那么我们为什么要探索 ar1[0...|n/2|]?
【问题讨论】:
-
如果m1太大而m2太小,则实际中位数不能在m1以上的ar1中,也不能在m2以下的ar2中。
标签: algorithm array-algorithms