I am trying to implement an array-based, fixed-size minimum binary heap ADT. As I was testing my program, all the functions I wrote seem to work fine except for finding the minimum element which is only supposed to return the integer value stored at the root node. The root node in this implementation is placed at index 1. The error I keep getting is the read-access violation. The following is the Binary Heap class definition and the implementation of the functions:
class BinaryHeap {
public:
BinaryHeap(int); // constructor that takes the capacity of the structure
~BinaryHeap(); // destructor
void insert(int); // inserts a new element to the heap
void deleteMin(); // removes the minimum element from the heap
int getMin(); // returns the minimum element int the heap, returns -1 if the heap is empty
private:
int *heap; // array to store the elements of the heap
int size; // keeps the number of elements in the heap
int capacity; // keeps the total capacity of the heap
void percolateDown(int);
void percolateUp(int);
void swap(int, int);
};
BinaryHeap::BinaryHeap(int capacity) {
this->capacity = capacity;
heap = new int[capacity+1];
size = 0;
}
BinaryHeap::~BinaryHeap() {
delete [] heap;
}
void BinaryHeap::insert(int element) {
if (size < capacity) {
size++;
heap[size] = element;
percolateUp(size);
}
else return;
}
void BinaryHeap::deleteMin() {
if (size < 1)
return;
else {
heap[1] = heap[size];
size--;
percolateDown(1);
}
}
int BinaryHeap::getMin() {
if (size < 1)
return -1;
else return heap[1];
}
void BinaryHeap::percolateDown(int hole) {
int leftChildIndex, rightChildIndex, minIndex;
leftChildIndex = hole * 2;
rightChildIndex = hole * 2 + 1;
if (rightChildIndex >= size) {
if (leftChildIndex >= size) return;
else minIndex = leftChildIndex;
}
else {
if (heap[leftChildIndex] <= heap[rightChildIndex])
minIndex = leftChildIndex;
else
minIndex = rightChildIndex;
}
if (heap[hole] > heap[minIndex]) {
swap(hole, minIndex);
percolateDown(minIndex);
}
}
void BinaryHeap::percolateUp(int index) {
int parentIndex(1);
if (index != 1) {
parentIndex = index / 2;
}
if (heap[parentIndex] > heap[index]) {
swap(parentIndex, index);
percolateUp(parentIndex);
}
}
void BinaryHeap::swap(int i, int j) {
int t = heap[i];
heap[i] = heap[j];
heap[j] = t;
}