0

I have got this Binary Heap implementation code in my text book using class. But i don't understand the necessity of key in building a heap.

#define MAXREAL 999999.0

class HeapItem
{
    public:
    int data; //actual data that is stored
    float key; //key value of the data, heap is constructed based on key
};
class MinHeap
{
    public:
    HeapItem * A; //stores heap items, e.g., nodes
    int heapLength;
    int * map;

    MinHeap() //constructor
    {
        A = new HeapItem[MAX_HEAP_SIZE];
        map = new int[MAX_HEAP_SIZE];
        heapLength = 0;
    }
//Fills the heap with an array of integers
//key values do not maintain heap property
//May be used in some algorithms such as dijkstra's shortest path
    void initialize(int v[], int n)
    {
        heapLength = n;
        for (int i = 0; i<n; i++) //nodes are stored from index 1 instead of 0 in the heap
        {
            A[i + 1].data = v[i];
            A[i + 1].key = MAXREAL;
            map[v[i]] = i + 1; //map tracks which vertex is stored at which heap node
        }
    }
}

What is the function of key and map in the MinHeap?

Leolime
  • 197
  • 1
  • 1
  • 11
  • 1
    Out of context, it's impossible to say what the purpose of the `key` field is. Can you give us a little bit more code so we can see how it's used? – Jim Mischel Apr 06 '17 at 18:02
  • I think values in circle are keys. The heap tree you gave is max-heap, not min-heap. If I am wrong, please correct me. – Yan Liu Feb 07 '19 at 18:41

2 Answers2

1

Here, your heap tree will be build on the basis of key value. For example: here value inside the red box is <code>key</code> and value inside cirle is <code>data</code>

For example: here value inside the red box is key and value inside cirle is data Since, it is a min heap, so it is build on the value of key. Root's key will be less than it's child.

shafayat hossain
  • 1,089
  • 1
  • 8
  • 13
0

In your case the key does nothing, it even presented in a comment:

//key values do not maintain heap property
//May be used in some algorithms such as dijkstra's shortest path

Also note that all the keys are assigned to MAXREAL basically the key can be used in order to keep the heap property.

In your case this can't be called a Heap. since the Heapify process is not called and there is no assumption on the order in the array. Basically it means that there is no particular order in your dataset so this is not a Minimum Heap.

Also in a Heap elements are stored from location 0 - which is the minimum.

It looks like the code is either incomplete or incorrect

antonpuz
  • 3,256
  • 4
  • 25
  • 48