-
Notifications
You must be signed in to change notification settings - Fork 19.7k
/
Copy pathMedianOfRunningArray.java
53 lines (46 loc) · 1.58 KB
/
MedianOfRunningArray.java
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
49
50
51
52
53
package com.thealgorithms.misc;
import java.util.Collections;
import java.util.PriorityQueue;
/**
* @author shrutisheoran
*/
public abstract class MedianOfRunningArray<T extends Number & Comparable<T>> {
private PriorityQueue<T> maxHeap;
private PriorityQueue<T> minHeap;
// Constructor
public MedianOfRunningArray() {
this.maxHeap = new PriorityQueue<>(Collections.reverseOrder()); // Max Heap
this.minHeap = new PriorityQueue<>(); // Min Heap
}
/*
Inserting lower half of array to max Heap
and upper half to min heap
*/
public void insert(final T e) {
if (!minHeap.isEmpty() && e.compareTo(minHeap.peek()) < 0) {
maxHeap.offer(e);
if (maxHeap.size() > minHeap.size() + 1) {
minHeap.offer(maxHeap.poll());
}
} else {
minHeap.offer(e);
if (minHeap.size() > maxHeap.size() + 1) {
maxHeap.offer(minHeap.poll());
}
}
}
/*
Returns median at any given point
*/
public T median() {
if (maxHeap.isEmpty() && minHeap.isEmpty()) {
throw new IllegalArgumentException("Enter at least 1 element, Median of empty list is not defined!");
} else if (maxHeap.size() == minHeap.size()) {
T maxHeapTop = maxHeap.peek();
T minHeapTop = minHeap.peek();
return calculateAverage(maxHeapTop, minHeapTop);
}
return maxHeap.size() > minHeap.size() ? maxHeap.peek() : minHeap.peek();
}
public abstract T calculateAverage(T a, T b);
}