-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathonline_data_median.h
More file actions
48 lines (40 loc) · 1.39 KB
/
Copy pathonline_data_median.h
File metadata and controls
48 lines (40 loc) · 1.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#ifndef CPP_ALGORITHM_ONLINE_DATA_MEDIAN_H
#define CPP_ALGORITHM_ONLINE_DATA_MEDIAN_H
#include <deque>
#include <queue>
#include <vector>
namespace OnlineDataMedian
{
/**
* \brief Find the median of a stream of numbers.
* \details Given a stream of numbers, find the median of the stream.
* \param stream a stream of numbers
* \return the median of the stream
*/
std::vector<double> FindMedian(std::deque<int>& stream);
}
// ----------------------------------------------------------------------------
inline std::vector<double> OnlineDataMedian::FindMedian(std::deque<int>& stream)
{
// min heap to store the larger half elements
auto min_heap = std::priority_queue<int, std::vector<int>, std::greater<>>{};
// max heap to store the smaller half elements
auto max_heap = std::priority_queue<int>{};
std::vector<double> result;
while (!stream.empty())
{
min_heap.emplace(stream.front());
stream.pop_front();
max_heap.emplace(min_heap.top());
min_heap.pop();
if (max_heap.size() > min_heap.size())
{
min_heap.emplace(max_heap.top());
max_heap.pop();
}
result.emplace_back(min_heap.size() == max_heap.size() ? (min_heap.top() + max_heap.top()) / 2.0
: min_heap.top());
}
return result;
}
#endif