I'm working on some homework involving Heaps, and I understand how they are structured. A heap must have each node satisfying the heap property,
the max-heap property is that for every node i other then the root, Heap[Parent(i)] >= Heap[i]
So at each node, the higher nodes have higher numbers, lower nodes have lower numbers. I understand this. But I can't see a use of a Heap other then to simply get the highest n numbers in a list. I don't see an easy way to search for a particular value and return the node, or to search for the n lowest number (in a max-heap). Both are relatively easy in a binary search tree.
Why wouldn't you just use a simple binary search tree? Or better yet, a balanced binary search tree?
EDIT: I should note, that this is not looking for an answer to a homework problem. The actual homework problem was writing pseudocode for parallel-p-heap for the insert() and extractMax() functions. And I already answered them. They just made me realize that I don't really understand Heaps.
The heap data structure has many applications.
Full and almost full binary heaps may be represented in a very space-efficient way using an array alone. The first (or last) element will contain the root. The next two elements of the array contain its children. The next four contain the four children of the two child nodes, etc. Thus the children of the node at position n would be at positions 2n and 2n+1 in a one-based array, or 2n+1 and 2n+2 in a zero-based array. This allows moving up or down the tree by doing simple index computations. Balancing a heap is done by swapping elements which are out of order. As we can build a heap from an array without requiring extra memory (for the nodes, for example), heapsort can be used to sort an array in-place.
One more advantage of heaps over trees in some applications is that construction of heaps can be done in linear time using Tarjan's algorithm.
Reference: http://en.wikipedia.org/wiki/Heap_%28data_structure%29
Because of the lack of pointers (heaps typically use an array-based data structure), the operations tend to be faster than for a binary tree. Also, some more complicated heaps (such as binomial) can be merged efficiently, which isn't easy to do for a binary tree. There is also information available at this SO question.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With