CS302 --- Heaps and Priority Queues

Brad Vander Zanden


Definition

Priority Queue: A data structure whose basic operations are:
  1. inserting new elements, and
  2. removing the largest or smallest element.

Example Uses


Operations we will Support

  1. Construct a priority queue from a set of items
  2. Insert a new item
  3. Remove the smallest item
  4. Delete an item
  5. Change the priority of an item

Elementary Implementations

  • Unordered list: Use an array of unordered items
    1. Construct: add items to the list one at a time -- O(n)
    2. Insert: add an item to the end of the list -- O(1)
    3. Remove smallest: search the list, remove the smallest item and return it -- O(n)

  • Ordered List: Use an array of ordered items
    1. Construct: requires a sort -- O(n log n)
    2. Insert: find the proper place in the list, move all smaller elements one position to the right -- O(n)
    3. Remove smallest: remove the Nth element -- O(1)

    Heap Data Structure


    Algorithms on Heaps

    Running Times

    Indirect Priority Queues

    If insert and deletemin are the only operations a priority queue needs to support, than the array implementation given above is adequate. However, if the priority queue also needs to support change priority and delete operations and wants to support them efficiently (i.e., in O(lg N) time), then indirect priority queues must be employed.

    The Problem

    In order to implement the change and delete operations in O(lg N) time, we need to eliminate the linear search that is required to find the item's position in the heap. We need to replace the linear search with a mechanism that allows us to find the item's heap position in O(lg N) time or less.

    The Solution

    The solution is to store an item's position with each item. When the item needs to be deleted or its priority needs to be changed, we look up its position and use that position to index into the array. In order to implement this change, we need to update position numbers as the items are moved around in the heap.