Test case:
8,7,5,2,3,6,9 (NOT min heap) (this is element A* for buildHeap function)
2,3,5,7,8,6,9 (min heap after calling build heap)
3,5,6,7,8,9 (after calling deleteMin) THIS IS INCORRECT
it should be this 3,7,5,9,8,6
I can't seem to find the problem with deleteMin i know my heapify is working but idk maybe im not seeing something.
Element Heap::deleteMin(Heap& heap){
Element deleted = heap.H[0];
heap.H[0] = heap.H[heap.size-1];
heap.size--;
cout<<deleted.getKey()<<" has been deleted from heap"<<endl;
for(int i=heap.capacity/2-1;i>=0;--i)
heapify(heap,i);
return deleted;
}
void Heap::heapify(Heap& heap,int index){
int smallest = 0;
int left = 2*index;
int right = 2*index+1;
if(left < heap.size && heap.H[left].getKey() < heap.H[index].getKey())
smallest=left;
else
smallest=index;
if(right < heap.size && heap.H[right].getKey() < heap.H[smallest].getKey())
smallest=right;
if(smallest != index){
int swapKey = heap.H[index].getKey();
heap.H[index].setKey(heap.H[smallest].getKey());
heap.H[smallest].setKey(swapKey);
heapify(heap,smallest);
}
}
void Heap::buildHeap(Heap& heap, Element* A){
for(int j=0;j<heap.capacity;++j){
heap.insert(heap,A[j]);
for(int i=heap.capacity/2-1;i>=0;--i)
heapify(heap,i);
}
}