Created
September 6, 2016 03:43
-
-
Save aajjbb/2999aa76c8013a8f00292868fa76c770 to your computer and use it in GitHub Desktop.
median.cpp
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Get median of a sequence in O(log(n)) | |
void balance() { | |
while (abs((int) (minHeap.size() - maxHeap.size())) > 1) { | |
if (minHeap.size() > maxHeap.size()) { | |
int tmp = minHeap.top(); | |
minHeap.pop(); | |
maxHeap.push(tmp); | |
} else { | |
int tmp = maxHeap.top(); | |
maxHeap.pop(); | |
minHeap.push(tmp); | |
} | |
} | |
} | |
int median_retrieve(void) { | |
if (minHeap.empty() && maxHeap.empty()) return 0; | |
if (minHeap.size() == maxHeap.size()) { | |
return min(minHeap.top(), maxHeap.top()); | |
} else { | |
if (minHeap.size() > maxHeap.size()) { | |
return minHeap.top(); | |
} else { | |
return maxHeap.top(); | |
} | |
} | |
} | |
void median_insert(int x) { | |
if (x > median_retrieve()) { | |
minHeap.push(x); | |
} else { | |
maxHeap.push(x); | |
} | |
balance(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment