Professional Documents
Culture Documents
10 Priority Queues (Heaps) PDF
10 Priority Queues (Heaps) PDF
(HEAPS)
Priority Queue
essentially a list of items in which each item
has associated with it a priority
items are inserted into a priority queue in any,
arbitrary order
items are withdrawn from a priority queue in
order of their priorities starting with the
highest priority item first
Model
Priority Queue
A priority queue is a container which provides
the following three operations:
enqueue
used to put objects into the container;
findMin
returns the smallest object in the container; and
dequeueMin
removes the smallest object from the container.
Priority Queue
Or in other implementations:
enqueue
used to put objects into the container;
deleteMin
finds,
returns, and removes the minimum element in
the priority queue.
Priority Queue
A priority queue is used to store a finite set of
keys drawn from a totally ordered set of
keys K
duplicate keys are allowed in priority queues
Applications
Operating systems
Sorting
Greedy algorithm implementations
Simple Implementations
Linked list
Insertin front at O(1)
Delete minimum by traversing the list at O(N)
Insert
Basic Heap Operation: Insert
General Strat
Percolate up
New element percolated up until correct location is
found
Create a hole
Basic Heap Operation: Insert
To insert 14
Insert 14
Basic Heap Operations
deleteMin
Find
minimum - easy!
Removing it – hard
A hole is created in removing the root
Last element X in the heap must move somewhere
Last element X
Basic Heap Operations
Delete 13
Move 14 up
Move 19 up
Basic Heap Operations
Delete 13
Move 26 up
Basic Heap Operations
Delete 13
Insert 31
Other operation: buildHeap
Other operation: buildHeap
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
150 80 40 30 10 70 110 100 20 90 60 50 120 140 130
Other operation: buildHeap
percolateDown(7)
Other operation: buildHeap
percolateDown(6)
Other operation: buildHeap
percolateDown(5)
Other operation: buildHeap
percolateDown(4)
Other operation: buildHeap
percolateDown(3)
Other operation: buildHeap
percolateDown(2)
Other operation: buildHeap
percolateDown(1)
Applications of Priority Queues
The selection problem
findthe kth largest element
Input is a list of N elements and an integer k.