I am having some trouble with my homework. I was asked to implement a priority queue, using a heap in C++.
While searching for code examples for creating a heap, I encountered many times in this definition:
An array A that represents a heap is an array with two attributes:
– length, the number of elements in the array
– heap-size, the number of heap elements stored in the array
So my question is this: what is A? do I need to implement it by myself (let’s say make a class heap which holds 3 fields- array of elements, length, and heap_size)?
I just don’t know how to start.
The binary heap data structure is usually drawn as a binary tree with certain properties, but is typically implemented using a plain array. The reason for this is that the array version uses less memory than the explicit binary tree and is a lot easier to manipulate. Consequently, the array A that you’re seeing described is the array that holds all the values in the heap.
The two fields you are seeing represent the raw total size of that array (length), which tracks how much storage space is available, and the number of elements within that array that you are actually using (heap-size). When you insert an element into the heap, you will need to make sure that space exists for it, possibly reallocating the array to be larger and copying over the existing elements, then will need to run a bubble-up operation to insert the new element into the heap.
Typically, though, you would sidestep the logic for maintaining the array and these two fields by layering the heap on top of a dynamic array, like the C++
std::vectoror JavaArrayList. That way, the logic to track storage space and grow the array is handled for you automatically.Depending on the assignment parameters, since this is being done in C++, you might want to look into the
std::make_heap,std::push_heap, andstd::pop_heapalgorithms from the<algorithm>header. They make it very easy to implement a heap on top of an existing container likestd::vector. In fact, this is how thestd::priority_queueclass is typically implemented.If you need to implement the heap operations yourself, you might want to check out the description of a binary heap given in this assignment handout, which seems to closely match the assignment you’ve been given.
Hope this helps!