-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinaryHeap.java
More file actions
136 lines (119 loc) · 2.21 KB
/
BinaryHeap.java
File metadata and controls
136 lines (119 loc) · 2.21 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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
public class BinaryHeap<T extends Comparable<T>>
{
public static final boolean MAX = true;
public static final boolean MIN = false;
private T[] elts;
private int last;
private boolean isMax;
public BinaryHeap()
{
elts = (T[])new Comparable[2];
elts[0] = null;
elts[1] = null;
last = 0;
isMax = true;
}
public BinaryHeap(boolean isMax)
{
elts = (T[])new Comparable[2];
elts[0] = null;
elts[1] = null;
last = 0;
this.isMax = isMax;
}
public int size()
{
return (last);
}
public boolean isEmpty()
{
return (last == 0);
}
private void doubleTabSize()
{
T[] newElts;
int i;
newElts = (T[])new Comparable[elts.length * 2];
i = 0;
while (i <= last)
{
newElts[i] = elts[i];
i++;
}
elts = null;
elts = newElts;
}
public T getTop()
{
if (last < 1)
return (null);
return (elts[1]);
}
public void add(T newElt)
{
int i;
T tmp;
if (last == elts.length - 1)
doubleTabSize();
last++;
elts[last] = newElt;
i = last;
while (i > 1 && ((isMax && elts[i].compareTo(elts[i / 2]) > 0) || (!isMax && elts[i].compareTo(elts[i / 2]) < 0)))
{
tmp = elts[i];
elts[i] = elts[i / 2];
elts[i / 2] = tmp;
i /= 2;
}
}
private boolean goodPosition(int i)
{
if (isMax && elts[i].compareTo(elts[i * 2]) >= 0 && (i * 2 + 1 > last || elts[i].compareTo(elts[i * 2 + 1]) >= 0))
return (true);
if (!isMax && elts[i].compareTo(elts[i * 2]) <= 0 && (i * 2 + 1 > last || elts[i].compareTo(elts[i * 2 + 1]) <= 0))
return (true);
return (false);
}
private int getToSwap(int i)
{
if (isMax)
{
if (i * 2 + 1 > last || elts[i * 2].compareTo(elts[i * 2 + 1]) > 0)
return (i * 2);
return (i * 2 + 1);
}
else
{
if (i * 2 + 1 > last || elts[i * 2].compareTo(elts[i * 2 + 1]) < 0)
return (i * 2);
return (i * 2 + 1);
}
}
public T pop()
{
T ret;
T tmp;
int i;
int to_swap;
if (last < 1)
return (null);
ret = elts[1];
elts[1] = elts[last];
last--;
i = 1;
while (i * 2 <= last)
{
if (goodPosition(i))
break;
to_swap = getToSwap(i);
tmp = elts[i];
elts[i] = elts[to_swap];
elts[to_swap] = tmp;
if (to_swap == i * 2)
i *= 2;
else
i = i * 2 + 1;
}
return (ret);
}
}