forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMedianOfRunningArray.java
More file actions
77 lines (67 loc) · 2.38 KB
/
MedianOfRunningArray.java
File metadata and controls
77 lines (67 loc) · 2.38 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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package com.thealgorithms.misc;
import java.util.Collections;
import java.util.PriorityQueue;
/**
* A generic abstract class to compute the median of a dynamically growing stream of numbers.
*
* @param <T> the number type, must extend Number and be Comparable
*
* Usage:
* Extend this class and implement {@code calculateAverage(T a, T b)} to define how averaging is done.
*/
public abstract class MedianOfRunningArray<T extends Number & Comparable<T>> {
private final PriorityQueue<T> maxHeap; // Lower half (max-heap)
private final PriorityQueue<T> minHeap; // Upper half (min-heap)
public MedianOfRunningArray() {
this.maxHeap = new PriorityQueue<>(Collections.reverseOrder());
this.minHeap = new PriorityQueue<>();
}
/**
* Inserts a new number into the data structure.
*
* @param element the number to insert
*/
public final void insert(final T element) {
if (!minHeap.isEmpty() && element.compareTo(minHeap.peek()) < 0) {
maxHeap.offer(element);
balanceHeapsIfNeeded();
} else {
minHeap.offer(element);
balanceHeapsIfNeeded();
}
}
/**
* Returns the median of the current elements.
*
* @return the median value
* @throws IllegalArgumentException if no elements have been inserted
*/
public final T getMedian() {
if (maxHeap.isEmpty() && minHeap.isEmpty()) {
throw new IllegalArgumentException("Median is undefined for an empty data set.");
}
if (maxHeap.size() == minHeap.size()) {
return calculateAverage(maxHeap.peek(), minHeap.peek());
}
return (maxHeap.size() > minHeap.size()) ? maxHeap.peek() : minHeap.peek();
}
/**
* Calculates the average between two values.
* Concrete subclasses must define how averaging works (e.g., for Integer, Double, etc.).
*
* @param a first number
* @param b second number
* @return the average of a and b
*/
protected abstract T calculateAverage(T a, T b);
/**
* Balances the two heaps so that their sizes differ by at most 1.
*/
private void balanceHeapsIfNeeded() {
if (maxHeap.size() > minHeap.size() + 1) {
minHeap.offer(maxHeap.poll());
} else if (minHeap.size() > maxHeap.size() + 1) {
maxHeap.offer(minHeap.poll());
}
}
}