Created
September 16, 2016 14:01
-
-
Save nichtemna/dfd455005d4688b4ef492bbaca676593 to your computer and use it in GitHub Desktop.
MedianHeap - data structure that returns median of inserted values. Implemented base on two heaps.
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
//http://stackoverflow.com/questions/15319561/how-to-implement-a-median-heap | |
class MedianHeap { | |
private PriorityQueue<Integer> minHeap = new PriorityQueue<>(10, new Comparator<Integer>() { | |
@Override | |
public int compare(Integer o1, Integer o2) { | |
return o2 - o1; | |
} | |
}); | |
private PriorityQueue<Integer> maxHeap = new PriorityQueue<>(); | |
public void add(int i) { | |
if (maxHeap.size() == 0 || i > getMedian()) { | |
maxHeap.add(i); | |
} else { | |
minHeap.add(i); | |
} | |
balance(); | |
} | |
private void balance() { | |
if (minHeap.size() > maxHeap.size() + 1) { | |
maxHeap.add(minHeap.poll()); | |
} else if (maxHeap.size() > minHeap.size() + 1) { | |
minHeap.add(maxHeap.poll()); | |
} | |
} | |
public double getMedian() { | |
if (maxHeap.size() > minHeap.size()) { | |
return maxHeap.peek(); | |
} else if (maxHeap.size() < minHeap.size()) { | |
return minHeap.peek(); | |
} else { | |
return ((double)maxHeap.peek() + (double)minHeap.peek()) / 2; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment