我无法理解getMedian方法背后的逻辑。如何评估中位数,元素数和元素总和之间的联系是什么?感谢有人能解释它的逻辑。
awk '{printf("%s", $0)}/,,,,/{print "\n"}' ORS="" file
100,"John","Clerk",,,,
101,"Dannis","Manager",,,,
102,"Michael","Senior Manager",,,,
103,"Donald","President of united states",,,,
答案 0 :(得分:5)
存在关系,因为它是频率表。你的想法有所不同,但让我举个例子。
1 1 1 3 3 4 4 4 5 5 5 5
如果这是数组,那么频率表将是: -
1 3 4 5
- - - -
3 2 3 4
所以这是median。 所以现在我正在添加每个元素计数并问我们问题,中位数在哪里?或者哪个是indexm,如果我认为我将覆盖中间元素?
现在我在这里检查总和是否> d / 2然后就完成了。我们发现了median.else,如果它少了,那么我仍然需要遍历其他元素才能到达数组的中间位置。如果它是sum == d / 2那么我们已经找到它但我们必须发送正确的位置。我们只是将它发送到较低的中间(例如1,1,1,1
)。
1 1 1 3 3 4 4 4 5 5 5 5
现在我检查一下我所在的所有地方是否已经过了?我介绍了3个要素。但它不是总数的一半(6)。
现在添加3个数字。这也不是。
现在我添加4个数字,包括我所涉及的8个元素。所以我覆盖了一半以上的元素。所以中位数在这里。
要求您查找10个整数数组的中位数。
[1 2 3 4 5 6 7 8 9]
然后中位数位于楼层(9/2)= 4的元素,这是5对吗?
[1 1 2 2 3 3 4 4 5]
位置楼层(9/2)= 4的中位元素在哪里,是3.对吗?
所以现在想想,
1 2 3 4 5
2 2 2 2 1
现在,您将尝试从头开始查找楼层(9/2)元素。这就是为什么你需要找到所有频率之和的原因。
希望你明白吗?
您需要做的是: -
N = number of elements.
F[] = frequency array
so if N is odd
find the element at floor(N/2)-th place and median is that element.
else
find the element at floor((N-1)/2) and floor(N/2) th position and return their average.
Finding the element is simple:
Find( F[], p) // find the element at position p
{
p=p+1
for i in [0..|F|]
cumulative+=F[i]
if cumulative == p
return this element.
else cumulative >p
return this element
}