If you are doing multiple queries in the same array, you can use the Segment Tree. Usually they are used to execute minimum / maximum range values ββand range sum queries, but you can change them to the median range.
The segment tree for dialing at n intervals uses O (n log n) memory and can be built in O (n log n) time. A range request can be made in O (log n).
An example of a median in a range segment tree:
You build a tree of segments from bottom to top (update from top to bottom):
[5] [3] [7] [1,2] [4] [6] [8] 1 2 3 4 5 6 7 8
Indexes covered by node:
[4] [2] [6] [0,1] [3] [5] [7] 0 1 2 3 4 5 6 7
The query for the median for indices in the range 4-6 will go along this value path:
[4] [5] 0 1 2 3 4 5 6 7
When searching for the median, you know the number of complete elements in the query (3), and the median in this range will be the second element (index 5). So you essentially search for the first node that contains this node index with the values ββ[1,2] (indexes 0,1).
Performing a search for a median of range 3-6 is a bit more complicated, because you need to look for two indexes (4,5) that are in the same node.
[4] [6] [5] 0 1 2 3 4 5 6 7
Segment tree
Minimum range query on a segment tree
Justin
source share