-
Notifications
You must be signed in to change notification settings - Fork 0
/
MedianHeapImpl.java
91 lines (77 loc) · 2.06 KB
/
MedianHeapImpl.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
82
83
84
85
86
87
88
89
90
91
import java.util.Arrays;
import java.util.Collections;
import java.util.NoSuchElementException;
import java.util.PriorityQueue;
public class MedianHeapImpl<Key extends Comparable<Key>> implements MedianHeap<Key> {
private PriorityQueue<Key> pqLeftHalf;
private PriorityQueue<Key> pqRightHalf;
public MedianHeapImpl() {
pqLeftHalf = new PriorityQueue<>(Collections.reverseOrder());
pqRightHalf = new PriorityQueue<>();
}
public MedianHeapImpl(Key[] keys) {
Arrays.sort(keys);
int len = keys.length;
for (int i = 0; i < len / 2; i++)
pqLeftHalf.add(keys[i]);
for (int i = len / 2; i < len; i++)
pqRightHalf.add(keys[i]);
}
@Override
public void insert(Key v) {
Key leftMax = pqLeftHalf.peek();
if((leftMax != null) && (less(v, leftMax)))
pqLeftHalf.add(v);
else
pqRightHalf.add(v);
equilibreHeaps();
}
@Override
public Key delMedian() {
int leftSize = pqLeftHalf.size();
int rightSize = pqRightHalf.size();
if(leftSize+rightSize == 0)
throw new NoSuchElementException("The Heap is empty");
if(leftSize > rightSize)
return pqLeftHalf.poll();
return pqRightHalf.poll();
}
@Override
public boolean isEmpty() {
int leftSize = pqLeftHalf.size();
int rightSize = pqRightHalf.size();
if(leftSize+rightSize == 0)
return true;
return false;
}
@Override
public Key median() {
int leftSize = pqLeftHalf.size();
int rightSize = pqRightHalf.size();
if(leftSize+rightSize == 0)
throw new NoSuchElementException("The Heap is empty");
if(leftSize > rightSize)
return pqLeftHalf.peek();
return pqRightHalf.peek();
}
@Override
public int size() {
return pqLeftHalf.size() + pqRightHalf.size();
}
private void equilibreHeaps(){
int leftSize = pqLeftHalf.size();
int rightSize = pqRightHalf.size();
if(leftSize > rightSize+1){
Key leftMax = pqLeftHalf.poll();
pqRightHalf.add(leftMax);
}else if(rightSize > leftSize+1){
Key rightMin = pqRightHalf.poll();
pqLeftHalf.add(rightMin);
}
}
private boolean less(Key a, Key b) {
if (a.compareTo(b) < 0)
return true;
return false;
}
}