@@ -128,26 +128,6 @@ public boolean add(T value) {
128
128
return true ;
129
129
}
130
130
131
- protected void heapUp (int idx ) {
132
- int nodeIndex = idx ;
133
- T value = this .array [nodeIndex ];
134
- while (nodeIndex >= 0 ) {
135
- int parentIndex = getParentIndex (nodeIndex );
136
- if (parentIndex < 0 ) break ;
137
- T parent = this .array [parentIndex ];
138
-
139
- if ((type == Type .MIN && parent != null && value .compareTo (parent ) < 0 )
140
- || (type == Type .MAX && parent != null && value .compareTo (parent ) > 0 )
141
- ) {
142
- // Node is greater/lesser than parent, switch node with parent
143
- this .array [parentIndex ] = value ;
144
- this .array [nodeIndex ] = parent ;
145
- } else {
146
- nodeIndex = parentIndex ;
147
- }
148
- }
149
- }
150
-
151
131
/**
152
132
* {@inheritDoc}
153
133
*/
@@ -177,8 +157,37 @@ private T remove(int index) {
177
157
return t ;
178
158
}
179
159
160
+ protected void heapUp (int idx ) {
161
+ int nodeIndex = idx ;
162
+ T value = this .array [nodeIndex ];
163
+ if (value ==null )
164
+ return ;
165
+
166
+ while (nodeIndex >= 0 ) {
167
+ int parentIndex = getParentIndex (nodeIndex );
168
+ if (parentIndex < 0 )
169
+ return ;
170
+
171
+ T parent = this .array [parentIndex ];
172
+
173
+ if ((type == Type .MIN && value .compareTo (parent ) < 0 )
174
+ || (type == Type .MAX && value .compareTo (parent ) > 0 )
175
+ ) {
176
+ // Node is greater/lesser than parent, switch node with parent
177
+ this .array [parentIndex ] = value ;
178
+ this .array [nodeIndex ] = parent ;
179
+ } else {
180
+ return ;
181
+ }
182
+ nodeIndex = parentIndex ;
183
+ }
184
+ }
185
+
180
186
protected void heapDown (int index ) {
181
187
T value = this .array [index ];
188
+ if (value ==null )
189
+ return ;
190
+
182
191
int leftIndex = getLeftIndex (index );
183
192
int rightIndex = getRightIndex (index );
184
193
T left = (leftIndex != Integer .MIN_VALUE && leftIndex < this .size ) ? this .array [leftIndex ] : null ;
@@ -225,7 +234,8 @@ protected void heapDown(int index) {
225
234
nodeToMoveIndex = leftIndex ;
226
235
}
227
236
// No node to move, stop recursion
228
- if (nodeToMove == null ) return ;
237
+ if (nodeToMove == null )
238
+ return ;
229
239
230
240
// Re-factor heap sub-tree
231
241
this .array [nodeToMoveIndex ] = value ;
0 commit comments