07 Handout 1
07 Handout 1
Heaps and Priority Queues or remove(). The dequeue operation starts with the
Heaps minimum element.
A heap is a complete binary tree where the value of PriorityQueue class from the java.util package.
each of each parent node is either higher or lower Example:
than the value of its child nodes. PriorityQueue<Integer> printer = new
These are the two (2) types of heap: PriorityQueue<>();
o Min Heap – The value of each parent node is To enqueue, use add() or offer(). To dequeue, use
less than or equal to the values of its child poll()
nodes.
o Max Heap – The value of each parent node is
greater than or equal to the values of its child
nodes.
Priority Queues
A priority queue is a special type of queue where
elements are processed based on their order (natural
or custom).
Priority queues can be implemented in Java
using the
Sample code to dequeue in Java based on natural A comparator is used to create a specific ordering for
order: PriorityQueue<Integer> printer = new a collection of objects.
PriorityQueue<>(); printer.add(9); To create a comparator in Java, use the Comparator
printer.add( interface and its methods such as comparing(),
7); comparingInt(), and compare().
printer.add(
Sample code to dequeue in Java based on a custom
1);
printer.add( order:
3); Comparator<String> comp =
Comparator.comparing(String::length);
while (!printer.isEmpty()) //:: indicates a method reference,
{ System.out.print(printer.remove() + " "); ContainingType::methodName PriorityQueue<String> prio =
} new PriorityQueue<>(comp); prio.add("cat");
Output: 1 3 7 9 prio.add("c");
Sample code to dequeue in Python based on natural prio.add("cats");
while (!prio.isEmpty()) {
order: System.out.println(prio.remove());
from queue import }
PriorityQueue prio = References:
PriorityQueue() Koffman, E. & Wolfgang, P. (2016). Data structures: Abstraction and design using
prio.put("dog") Java.
prio.put("d") Hoboken: John Wiley & Sons, Inc.
Oracle Docs. (n.d.). Citing sources. Retrieved
prio.put("dogs")
from https://docs.oracle.com/javase/8/docs/api/java/util/package-
while not prio.empty(): summary.html
next_item = prio.get() Python Software Foundation. (n.d.). The Python tutorial. Retrieved
print(next_item) from https://docs.python.org/3/tutorial/index.html