I am trying to implement a min priority queue using a binary min heap based on the description from "Introduction to Algorithms, Third Edition" and have a couple of questions.
The book says that we often need to store a handle (pointer or integer) to the application object in each heap element and that we also need to store a handle (array index) to the heap element in each application object.
1) Would the heap implementation typically look something like this then?
template <class KeyType, class ObjectType>
struct HeapElement
{
KeyType key;
ObjectType* pObject;
};
template <class KeyType, class ObjectType>
class MinHeap
{
// ...
private:
std::vector< HeapElement<KeyType, ObjectType> > data;
};
And then the ObjectType class would also store the heapIndex:
class Foo
{
// ...
int heapIndex;
};
2) Is the min priority queue and binary min heap typically implemented as a single class or is the min priority queue usually implemented as its own class with a private heap class member?
class MinPriorityQueue
{
// ...
private:
MinHeap minHeap;
};
The reason I ask is because if you look at the implementation for something like ExtractMin()
, it requires that you manipulate the heap data:
int min = data[0]; // data: private heap data member
heapSize--; // heapSize: private heap data member
MinHeapify(0); // MinHeapify: private heap member function
So maybe the min priority queue class should act as a wrapper class?
T MinPriorityQueue::ExtractMin()
{
return minHeap.ExtractMin();
}
In that case, the binary min heap class might implement Min()
, ExtractMin()
, DecreaseKey()
, and Insert()
and contain the functionality for both a binary min heap and min priority queue. Then there would be no need for a MinPriorityQueue class at all.
The scope of the question is implementing heaps/priority queues for job interviews. Any thoughts on this?