phishman3579 / java-algorithms-implementation

Algorithms and Data Structures implemented in Java

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

BinaryHeapArray::clear function is broken

lkn2993 opened this issue · comments

Here's a custom test case written:

BinaryHeap.BinaryHeapArray<Integer> aHeapMax = new BinaryHeap.BinaryHeapArray<Integer>(BinaryHeap.Type.MAX);
aHeapMax.add(10);
aHeapMax.add(11);
aHeapMax.clear();
assertNull(aHeapMax.getHeadValue()); // we expect null here

We expect that the head of BinaryHeapArray becomes null on clear, but it does not, and BinaryHeapArray::getHeadValue and BinaryHeapArray::toString functions return the first value of the heap array despite asking for a clear.

One possible fix is to explicitly make head null when clear function is invoked:

@Override
        public void clear() {
            size = 0;
            this.array[size] = null;
        }

Thanks for pointing this out. You are right, although I think the solution is different. getHeadValue() should check size==0 and return NULL when true.

I'll do that then.