Is it possible to make efficient pointer-based binary heap implementations?

前端 未结 6 1871
无人共我
无人共我 2020-12-14 12:22

Is it even possible to implement a binary heap using pointers rather than an array? I have searched around the internet (including SO) and no answer can be found.

T

6条回答
  •  不思量自难忘°
    2020-12-14 12:50

    There are a number of comments pointing out that by a strict definition it is possible to implement a binary heap as a tree and still call it a binary heap.

    Here is the problem -- there is never a reason to do so since using an array is better in every way.

    If you do searches to try to find information on how to work with a heap using pointers you are not going to find any -- no one bothers since there is no reason to implement a binary heap in this way.

    If you do searches on trees you will find lots of helpful materials. This was the point of my original answer. There is nothing that stops people from doing it this way but there is never a reason to do so.

    You say -- I have to do so, I've got an legacy system and I have pointers to nodes I need to put them in a heap.

    Make an array of those pointers and work with them in this array as you would a standard array based heap, when you need the contents dereference them. This will work better than any other way of implementing your system.

    I can think of no other reason to implement a heap using pointers.


    Original Answer:

    If you implement it with pointers then it is a tree. A heap is a heap because of how you can calculate the location of the children as a location in the array (2 * node index +1 and 2 * node index + 2).

    So no, you can't implement it with pointers, if you do you've implemented a tree.

    Implementing trees is well documented if you search you will find your answers.

提交回复
热议问题