forked from rampatra/Algorithms-and-Data-Structures-in-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMedianOfStream.java
81 lines (73 loc) · 2.31 KB
/
MedianOfStream.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package com.rampatra.arrays;
import com.rampatra.base.MaxHeap;
import com.rampatra.base.MinHeap;
/**
* Created by IntelliJ IDEA.
*
* @author rampatra
* @since 9/12/15
* @time: 11:19 PM
*/
public class MedianOfStream {
/**
* @param med
* @param elem
* @param maxHeap
* @param minHeap
* @return
*/
public static int getMedianOfStream(int med, int elem, MaxHeap maxHeap, MinHeap minHeap) {
switch (compare(maxHeap.getSize(), minHeap.getSize())) {
case 0: // sizes of maxHeap and minHeap are same
if (elem < med) {
maxHeap.insert(elem);
med = maxHeap.findMax();
} else {
minHeap.insert(elem);
med = minHeap.findMin();
}
break;
case 1: // size of maxHeap greater than minHeap
if (elem < med) {
minHeap.insert(maxHeap.extractMax());
maxHeap.insert(elem);
} else {
minHeap.insert(elem);
}
med = (maxHeap.findMax() + minHeap.findMin()) / 2;
break;
case -1: // size of maxHeap smaller than minHeap
if (elem < med) {
maxHeap.insert(elem);
} else {
maxHeap.insert(minHeap.extractMin());
minHeap.insert(elem);
}
med = (maxHeap.findMax() + minHeap.findMin()) / 2;
break;
}
return med;
}
static void printMedianOfStream(int[] a) {
int m = 0;
MaxHeap maxHeap = new MaxHeap(a);
MinHeap minHeap = new MinHeap(a);
// calling in a loop so at to resemble a stream
for (int i = 0; i < a.length; i++) {
m = getMedianOfStream(m, a[i], maxHeap, minHeap);
}
System.out.println(m);
}
static int compare(int a, int b) {
if (a == b) {
return 0;
} else {
return a < b ? -1 : 1;
}
}
public static void main(String[] args) {
printMedianOfStream(new int[]{5, 15, 1, 3, 2, 8, 7, 9, 10, 6, 11, 4});
printMedianOfStream(new int[]{5, 15, 1});
printMedianOfStream(new int[]{5, 15, 10, 20});
}
}