Reputation: 2151
I need to find a data structure that meets these requirements:
For the first three requirements, this works: keep the n/2 smallest items in a max heap and the n/2 largest in a min heap. The roots of those heaps will be the lower/upper median.
But I'm stuck with the 4th requirement. Any ideas?
Upvotes: 5
Views: 776
Reputation: 24677
Keep the n/2 largest items in a min heap. For the n/2 smallest items maintain a pair of max and min heaps. Heaps in this pair are augmented with index of the same element in the paired heap, so that any heap modification updates indexes in the paired heap for all moved items.
Paired heap explanations
Both heaps contain exactly the same set of items. Along with each item there is an additional index field. When heap is modified, some items may change their places. If an item is moved from index x
to index y
, corresponding item in the paired heap must be notified. This corresponding item is easily located in paired heap with moved item's index field. And the contents of the corresponding item's index field is changed from x
to y
. This allows all heap items to know exactly where their pairs are located. Keeping corresponding items in both heaps in-sync allows (while extracting largest item from the max heap or 2nd smallest item from the min heap) extract corresponding item from the paired heap. And keeping heaps in-sync does not increase any of the complexity requirements.
Upvotes: 3