template <class T>
void priorityQueue<T>::heapDown(int i)
{
int l = leftChild(i);
int r = rightChild(i);
int x = 0;
int n = size();
if (l < n && arr[i] < arr[l])
{
x = l;
if (r < n && arr[l] < arr[r])
x = r;
}
elseif (r < n && arr[i] < arr[r])
x = r;
if (x != 0)
{
T temp = arr[x];
arr[x] = arr[i];
arr[i] = temp;
heapDown(x);
}
}
template<class T>
void priorityQueue<T>::heapify(T arr[], int size){
int i = (size)/2;
while(i >= 0){
heapDown(i);
i -= 1;
}
}
template<class T>
T priorityQueue<T>::remove(){
if(size() == 0){
throw runtime_error("Warning: size < 0");
}
T highestPriority = arr[i];
int indexOfRoot = 0;
arr[indexOfRoot] = arr[size()-1]; // size() returns the num of elements in the array
currentSize -=1;
reheapDown(indexOfRoot); // or heapify(arr, size()) ???
// heapify(arr, size()); // ???
return highestPriority;
}
I figured out the answer to my question, and I decided to share it here.
If you call heapify(arr, size()), it will actually cause output errors, and I managed to realize this issue during my testing process.
It is better to call reheapDown(0), 0 indicating the index of the root. If you do this, the remove function will always remove an element at O(log n) time complexity.
There might be other ways to implement this, but I figured out my method results in the right output by testing my remove function multiple times, and my max heap array was able to keep its maximum heap property after each removal until size() resulted in 0.