


[2,3,4] - median is 3.
[2,3] - median is floor((2+3)/2) = 2.
The first line of input contains a single integer T, representing the number of test cases or queries to be run.
Then the T test cases follow.
The first line of each test case contains the number of elements, N, in the input data stream.
The second line of each test case contains N space separated elements of the input data stream.
For each test case, print the median of the elements after each incoming element. Each median value is separated by a single space.
The output of each test case is printed in a separate line.
You do not need to print anything, just return the vector of medians after each element is read from the stream.
1 <= T <= 10
1 <= N <= 10^4
0 <= data <= 10^8
Where T is the number of test cases, N is the number of elements in the data stream.
Time Limit : 1 sec
Store the incoming data elements in a vector. Sort the vector everytime you need to output the median.
If we sort the data as it appears, the median can be located easily. Insertion Sort is one such algorithm that sorts the data appeared so far. At any instance of sorting, say after sorting i-th element, the first ‘i’ elements of the array are sorted. Insertion sort considers data sorted so far while inserting the next element.
The idea is to use two heaps, one max - heap and one min - heap. The max-heap will be used to represent elements that are less than the effective median, and min-heap will be used to represent the elements that are greater than the effective median.
After processing the incoming element, the number of elements in heaps differ utmost by 1 element and this will be the case when there are odd number of elements. Thus the heap having more number of elements will give its root value as median. When both the heaps contains same number of elements, average of heaps root data is the effective median.
a. Add num to max-heap ‘lo’. Since ‘lo’ received a new element, we must do a balancing step for ‘lo’ and offer its largest element to ‘hi’.
b. The min-heap ‘hi’ might end up holding more elements than max-heap ‘lo’, after previous operation. We fix that by removing the smallest element from ‘hi’ and offering it to ‘lo’.