When would you want to use a Heap?

Technology CommunityCategory: Heaps and MapsWhen would you want to use a Heap?
VietMX Staff asked 3 years ago

The characteristic of a heap is that it is a structure that maintains data semiordered; thus, it is a good tradeoff between the cost of maintaining a complete order ant the cost of seaching through random chaos. That characteristic is used on many algorithms, such as selectionordering, or classification.

Also consider:

  • Use it whenever you need quick access to the largest (or smallest) item, because that item will always be the first element in the array or at the root of the tree
  • Good for selection algorithms (finding the min or max). A heap allows access to the min or max element in constant time, and other selections (such as median or kth-element) can be done in sub-linear time on data that is in a heap
  • Priority Queue. A priority queue is an abstract concept like “a list” or “a map”; just as a list can be implemented with a linked list or an array, a priority queue can be implemented with a heap or a variety of other methods.
  • Anytime when you sort a temporary list, you should consider heaps. Heapsort is one of the best sorting methods being in-place and with no quadratic worst-case scenarios.
  • A heap data structure is useful to merge many already-sorted input streams into a single sorted output stream
  • Graph algorithms. By using heaps as internal traversal data structures, run time will be reduced by polynomial order. Examples of such problems are Prim’s minimal spanning tree algorithm and Dijkstra’s shortest path problem.

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.