find-median-from-data-stream 1.0.0
Find Median from Data Stream
Loading...
Searching...
No Matches
MedianFinder Class Reference
Collaboration diagram for MedianFinder:

Public Member Functions

 MedianFinder ()
 
void addNum (int num)
 
double findMedian ()
 

Private Attributes

priority_queue< int > max_heap
 
priority_queue< int, vector< int >, greater< int > > min_heap
 

Detailed Description

Definition at line 5 of file main.cpp.

Constructor & Destructor Documentation

◆ MedianFinder()

MedianFinder::MedianFinder ( )
inline

Definition at line 12 of file main.cpp.

12{}

Member Function Documentation

◆ addNum()

void MedianFinder::addNum ( int  num)
inline

Definition at line 14 of file main.cpp.

15 {
16 if (max_heap.empty() || num <= max_heap.top())
17 {
18 cout << "adding " << num << " to max heap" << endl;
19 max_heap.push(num);
20 }
21 else
22 {
23 cout << "adding " << num << " to min heap" << endl;
24 min_heap.push(num);
25 }
26
27 // balancing heaps
28 if (max_heap.size() > min_heap.size() + 1)
29 {
30 cout << "moving " << max_heap.top() << " from max to min heap" << endl;
31 min_heap.push(max_heap.top());
32 max_heap.pop();
33 }
34 else if (min_heap.size() > max_heap.size())
35 {
36 cout << "moving " << min_heap.top() << " from min to max heap" << endl;
37 max_heap.push(min_heap.top());
38 min_heap.pop();
39 }
40 }
priority_queue< int > max_heap
Definition main.cpp:8
priority_queue< int, vector< int >, greater< int > > min_heap
Definition main.cpp:9

References max_heap, and min_heap.

Referenced by main().

◆ findMedian()

double MedianFinder::findMedian ( )
inline

Definition at line 42 of file main.cpp.

43 {
44 if (max_heap.size() == min_heap.size())
45 return (max_heap.top() + min_heap.top()) / 2.0;
46 else
47 return max_heap.top();
48 }

References max_heap, and min_heap.

Referenced by main().

Field Documentation

◆ max_heap

priority_queue<int> MedianFinder::max_heap
private

Definition at line 8 of file main.cpp.

Referenced by addNum(), and findMedian().

◆ min_heap

priority_queue<int, vector<int>, greater<int> > MedianFinder::min_heap
private

Definition at line 9 of file main.cpp.

Referenced by addNum(), and findMedian().


The documentation for this class was generated from the following file: