To insert an item into the heap, you can put it anywhere and swap it with your parent until the heap restriction is again valid. Swap-with-parent is an operation that preserves the integrity of the binary tree structure of the heap. This means that a heap of size N will be represented as an array of N-cells, and you can add a new element at logarithmic time.
A binary search tree can be represented as an array of size N using the same presentation structure as the heap (children 2n and 2n + 1), but inserting an element in this way is much more difficult, because unlike the heap constraint, to limit the binary search tree twists are required to extract a balanced tree. Thus, either you manage to save the N node tree in an N-cell array at a price higher than the logarithmic price, or you lose space by saving the tree in a larger array (if my memory serves, the red back tree can spend up to 50% of your array).
Thus, a binary search tree in an array is interesting only if the data inside is constant. And if so, then you do not need a heap structure (children 2n and 2n + 1): you can just sort your array and use binary search .
Victor nicollet
source share