I'm trying to remove(Comparable e) object say remove(2), but when I try to remove it removes the incorrect node in the heap and not the one that I want it to be removed.
This is what the output looks like.
The heap before removing Redwoods NP:
Bryce Canyon NP Redwoods NP Joshua Tree NP Zion NP Yosemite NP Lassen Volcanic NP
[
null,
Bryce Canyon NP,
Redwoods NP,
Joshua Tree NP,
Zion NP,
Yosemite NP,
Lassen Volcanic NP
]
After removing Redwoods NP:
Bryce Canyon NP Redwoods NP Joshua Tree NP Zion NP Redwoods NP
[
null,
Bryce Canyon NP,
Redwoods NP,
Joshua Tree NP,
Zion NP,
Redwoods NP,
Lassen Volcanic NP
]
BUILD SUCCESSFUL (total time: 1 second)
Expected
[
Bryce Canyon NP,
Joshua Tree NP,
Zion NP,
Yosemite NP,
Lassen Volcanic NP
]
My code
public void remove(Comparable e) throws NoSuchElementException {
if (size == 0) {
throw new NoSuchElementException("Heap is empty! Nothing to be removed");
}
Comparable toRemove = e;
System.out.println(Arrays.toString(heapData));
Comparable temp = heapData[size-1];
heapData[size-1] = toRemove;
toRemove = temp;
size--;
maxHeapify(heapData,size);
}
My Add(Comparable e) code method
public void add(Comparable e) {
if (size == heapData.length - 1) {
doubleSize();
}
int position = ++size;
for (; position > 1 && e.compareTo(heapData[position / 2]) < 0; position = position / 2) {
heapData[position] = heapData[position / 2];
maxHeapify(heapData, position);
}
heapData[position] = e;
}