Back

ⓘ Heap (data structure)




Heap (data structure)
                                     

ⓘ Heap (data structure)

In computer science, a heap is a type of tree that satisfies the heap property. Heaps are useful when you need to remove the item with the highest value. A common implementation of a heap is the binary heap in which the tree is a complete binary tree.

                                     

1. Heap property

  • In a min-heap, the value of each item is greater than or equal to the value of its parent, with the minimum-value item at the root.
  • In a max-heap, the value of each item is less than or equal to the value of its parent, with the maximum-value item at the root.
                                     

2. Operations

  • find: return a maximum item of a max-heap or a minimum item of a min-heap.
  • insert: add a new item to the heap.
  • is-empty: return true if the heap is empty, false otherwise.
  • size: return the number of items in the heap.
  • delete: removes the root of a max-heap or min-heap.
  • extract: returns the maximum item from a max-heap or minimum item from a min-heap after removing it.
                                     

3. Maintaining the heap property

  • delete: remove the root; swap it with the item at the bottom rightmost location; swap the new root downwards with the smaller of its children for a min-heap until the heap property is preserved.
  • insert: insert the item at the bottom rightmost location; swap the item with its parent until the heap property is preserved.