分而治之 - 找到数组的中位数

时间:2014-02-22 10:38:29

标签: algorithm proof divide-and-conquer

假设我们有一个大小为2n的所有独特元素的数组。

假设我们将数组拆分为2个大小为n的数组,并且我们有一个特殊的常量时间查找,以便找到该特定数组的第k个最小元素,如果1&lt; = k <= n,那么对于[4 5 6 ],k = 2返回5.

那么找到中位数的Θ(log(n))算法是什么?中位数被定义为2个数组之间的第n个最低元素。如果数组是[1 2 3 4 5 6],则中位数通常为(3 + 4)/ 2,但我们只选择较小的一个为3。 我的尝试即:

2n = 6  [1 2 3 4 5 6]
n = 3   [1 2 3] [4 5 6] (not necessarily sorted, but we have the constant time lookup, so sorting is irrelevant)
Step 1) use lookup where k = n to find the kth smallest element for each array
[1 2 3] [4 5 6]
     ^       ^ (if k = 3, we get 3 for the first array, 6 for the second array)
Step 2) compare the 2 values we got and choose the smaller one. 3 is the median where median is defined as the nth lowest element between the 2 arrays.

首先,这是Θ(log(n))时间的正确算法吗?其次,证明正确性(它找到中位数)是什么样的?我相信这将是通过归纳。

1 个答案:

答案 0 :(得分:-1)

选择(中位数计算是一种特殊情况)无法在O(log n)时间内求解。您可以使用Quickselect等算法在O(n)时间内解决它。

相关问题