Error in minHeap Implementation for C++

this is a beginner work and I'd like te have a heap which contains any item inserted by me. However, when I insert the values, if I delete the min value of this coded heap twice, I get the min value uncorrect.I could not find where the mistake is. Could you please help me?


Code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
    
    void BinaryHeap::percolateDown(int hole) {
    	int child = hole*2;
    	while (child < size) {
    		if (child < size-1 && heap[child] < heap[child+1]) {
    			child++;
    		}
    		if (heap[hole] < heap[child]) {
    			swap(heap[hole],heap[child]);
    			hole = child;
    			child = child*2;
    		} else {
    			break;
    		}
    		child++;
    	}
    }
    
    }
Last edited on
The error is most likely with this line:
38
39
40
41
42
if (heap[hole] < heap[child]) {
    swap(heap[hole],heap[child]); //this
    hole = child;
    child = child*2;
}


Fix:
1
2
3
4
5
6
7
8
9
10
void BinaryHeap::percolateDown(int hole) {
    for (int child = hole * 2; child < size; hole++, child = hole * 2) {
    	if (heap[hole] > heap[child]) {
    		this->swap(hole, child); // give index rather than value
    	}
    	if (heap[hole] > heap[child + 1]) {
    		this->swap(hole, child + 1); //give it index rather than value
    	}
    }
}
Last edited on
Topic archived. No new replies allowed.