[Solved] Building a heap principles- implementing in C++ [closed]


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::vector or Java ArrayList. 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, and std::pop_heap algorithms from the <algorithm> header. They make it very easy to implement a heap on top of an existing container like std::vector. In fact, this is how the std::priority_queue class 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!

5

solved Building a heap principles- implementing in C++ [closed]