|
@@ -134,10 +134,89 @@ public class BinaryHeap<E extends Comparable<E>> implements PriorityQueue<E> {
|
134
|
134
|
this.arraySet(index, x);
|
135
|
135
|
this.percolateUp(index);
|
136
|
136
|
}
|
|
137
|
+
|
|
138
|
+ // recursive version
|
|
139
|
+ private int find(int indexStart, E x) throws ElementNotFoundException {
|
|
140
|
+
|
|
141
|
+ //it's a heap so uses it to find a log(n) speed the element
|
|
142
|
+
|
|
143
|
+ int ileft = indexLeft(indexStart);
|
|
144
|
+ int iright = ileft + 1;
|
|
145
|
+ boolean hasRight = iright < this.currentSize;
|
|
146
|
+ boolean hasLeft = ileft < this.currentSize;
|
|
147
|
+
|
|
148
|
+ if(hasRight) {
|
|
149
|
+ try {
|
|
150
|
+ if(x.compareTo(this.array.get(iright)) == 0) {
|
|
151
|
+ return iright;
|
|
152
|
+ }
|
|
153
|
+ else if(x.compareTo(this.array.get(iright)) > 0) {
|
|
154
|
+ return find(iright, x);
|
|
155
|
+ }
|
|
156
|
+ }catch (ElementNotFoundException e) {
|
|
157
|
+ //do nothing...
|
|
158
|
+ }
|
|
159
|
+ }
|
|
160
|
+
|
|
161
|
+ if(hasLeft) {
|
|
162
|
+ try {
|
|
163
|
+ if(x.compareTo(this.array.get(ileft)) == 0) {
|
|
164
|
+ return ileft;
|
|
165
|
+ }
|
|
166
|
+ else if(x.compareTo(this.array.get(ileft)) > 0) {
|
|
167
|
+ return find(ileft, x);
|
|
168
|
+ }
|
|
169
|
+ }catch (ElementNotFoundException e) {
|
|
170
|
+ //do nothing...
|
|
171
|
+ }
|
|
172
|
+ }
|
|
173
|
+
|
|
174
|
+ //here we dont find anything from this index, throw exception
|
|
175
|
+ throw new ElementNotFoundException(x);
|
|
176
|
+ }
|
|
177
|
+
|
|
178
|
+ @Override
|
|
179
|
+ public int find(E x) throws ElementNotFoundException {
|
|
180
|
+
|
|
181
|
+ if(this.currentSize == 0) {
|
|
182
|
+ throw new ElementNotFoundException(x);
|
|
183
|
+ }
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+ /*int index = this.array.indexOf(x);
|
|
187
|
+
|
|
188
|
+ if(index < 0 || index >= this.currentSize) {
|
|
189
|
+ throw new ElementNotFoundException(x);
|
|
190
|
+ }
|
|
191
|
+ else {
|
|
192
|
+ return index;
|
|
193
|
+ }*/
|
|
194
|
+
|
|
195
|
+ //try to see if it's root
|
|
196
|
+ if(this.array.get(0).compareTo(x) == 0) {
|
|
197
|
+ return 0;
|
|
198
|
+ }
|
|
199
|
+
|
|
200
|
+ //so now we need to find deeper.
|
|
201
|
+ return find(0, x);
|
|
202
|
+ }
|
137
|
203
|
|
138
|
204
|
@Override
|
139
|
205
|
public void remove(E x) throws ElementNotFoundException {
|
140
|
|
- // TODO:
|
|
206
|
+ // first step, find the element on the heap
|
|
207
|
+
|
|
208
|
+ int myIndex = find(x);
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+ //now we have the element of the object to remove
|
|
212
|
+ //so it's like deleting root, but instead of root it's index of x
|
|
213
|
+
|
|
214
|
+ E lastItem = this.array.get(--this.currentSize);
|
|
215
|
+ this.arraySet(myIndex, lastItem);
|
|
216
|
+ this.percolateUp(myIndex);
|
|
217
|
+ this.percolateDown(myIndex);
|
|
218
|
+
|
|
219
|
+
|
141
|
220
|
}
|
142
|
221
|
|
143
|
222
|
@Override
|