SlideShare a Scribd company logo
Emory University Logo Guidelines
-
Priority Queues
Data Structures and Algorithms
Emory University
Jinho D. Choi
Emory University Logo Guidelines
-
Priority Queue
2
Emory University Logo Guidelines
-
Priority Queue
• Priority queue
2
Emory University Logo Guidelines
-
Priority Queue
• Priority queue
- Add: insert a comparable key.
2
Emory University Logo Guidelines
-
Priority Queue
• Priority queue
- Add: insert a comparable key.
- Remove: find and remove the key with the highest priority.
2
Emory University Logo Guidelines
-
Priority Queue
• Priority queue
- Add: insert a comparable key.
- Remove: find and remove the key with the highest priority.
• Application
2
Emory University Logo Guidelines
-
Priority Queue
• Priority queue
- Add: insert a comparable key.
- Remove: find and remove the key with the highest priority.
• Application
- Scheduling.
2
Emory University Logo Guidelines
-
Priority Queue
• Priority queue
- Add: insert a comparable key.
- Remove: find and remove the key with the highest priority.
• Application
- Scheduling.
• Implementation
2
Emory University Logo Guidelines
-
Priority Queue
• Priority queue
- Add: insert a comparable key.
- Remove: find and remove the key with the highest priority.
• Application
- Scheduling.
• Implementation
- Lazy vs. Eager.
2
Emory University Logo Guidelines
-
Priority Queue
• Priority queue
- Add: insert a comparable key.
- Remove: find and remove the key with the highest priority.
• Application
- Scheduling.
• Implementation
- Lazy vs. Eager.
- Heap.
2
Emory University Logo Guidelines
-
Abstract Priority Queue
3
public abstract class AbstractPriorityQueue<T extends Comparable<T>>
{
protected Comparator<T> comparator;
public AbstractPriorityQueue(Comparator<T> comparator)
{
this.comparator = comparator;
}
...
}
Emory University Logo Guidelines
-
Abstract Priority Queue
3
public abstract class AbstractPriorityQueue<T extends Comparable<T>>
{
protected Comparator<T> comparator;
public AbstractPriorityQueue(Comparator<T> comparator)
{
this.comparator = comparator;
}
...
}
Emory University Logo Guidelines
-
Abstract Priority Queue
3
public abstract class AbstractPriorityQueue<T extends Comparable<T>>
{
protected Comparator<T> comparator;
public AbstractPriorityQueue(Comparator<T> comparator)
{
this.comparator = comparator;
}
...
}
class?
Emory University Logo Guidelines
-
Abstract Priority Queue
3
public abstract class AbstractPriorityQueue<T extends Comparable<T>>
{
protected Comparator<T> comparator;
public AbstractPriorityQueue(Comparator<T> comparator)
{
this.comparator = comparator;
}
...
}
class? interface?
Emory University Logo Guidelines
-
Abstract Priority Queue
3
public abstract class AbstractPriorityQueue<T extends Comparable<T>>
{
protected Comparator<T> comparator;
public AbstractPriorityQueue(Comparator<T> comparator)
{
this.comparator = comparator;
}
...
}
class? genericinterface?
Emory University Logo Guidelines
-
Abstract Priority Queue
3
public abstract class AbstractPriorityQueue<T extends Comparable<T>>
{
protected Comparator<T> comparator;
public AbstractPriorityQueue(Comparator<T> comparator)
{
this.comparator = comparator;
}
...
}
class? genericinterface?
Emory University Logo Guidelines
-
Abstract Priority Queue
3
public abstract class AbstractPriorityQueue<T extends Comparable<T>>
{
protected Comparator<T> comparator;
public AbstractPriorityQueue(Comparator<T> comparator)
{
this.comparator = comparator;
}
...
}
class? genericinterface?
Emory University Logo Guidelines
-
Abstract Priority Queue
3
public abstract class AbstractPriorityQueue<T extends Comparable<T>>
{
protected Comparator<T> comparator;
public AbstractPriorityQueue(Comparator<T> comparator)
{
this.comparator = comparator;
}
...
}
class? genericinterface?
Emory University Logo Guidelines
-
Abstract Priority Queue
3
public abstract class AbstractPriorityQueue<T extends Comparable<T>>
{
protected Comparator<T> comparator;
public AbstractPriorityQueue(Comparator<T> comparator)
{
this.comparator = comparator;
}
...
}
class? genericinterface?
Emory University Logo Guidelines
-
Abstract Priority Queue
4
public abstract class AbstractPriorityQueue<T extends Comparable<T>>
{
...
abstract public void add(T key);
abstract protected T removeAux();
abstract public int size();
public boolean isEmpty()
{
return size() == 0;
}
public T remove()
{
if (isEmpty()) throw new NoSuchElementException("No key exists.");
return removeAux();
}
}
Emory University Logo Guidelines
-
Abstract Priority Queue
4
public abstract class AbstractPriorityQueue<T extends Comparable<T>>
{
...
abstract public void add(T key);
abstract protected T removeAux();
abstract public int size();
public boolean isEmpty()
{
return size() == 0;
}
public T remove()
{
if (isEmpty()) throw new NoSuchElementException("No key exists.");
return removeAux();
}
}
abstract
methods
Emory University Logo Guidelines
-
Abstract Priority Queue
4
public abstract class AbstractPriorityQueue<T extends Comparable<T>>
{
...
abstract public void add(T key);
abstract protected T removeAux();
abstract public int size();
public boolean isEmpty()
{
return size() == 0;
}
public T remove()
{
if (isEmpty()) throw new NoSuchElementException("No key exists.");
return removeAux();
}
}
abstract
methods
defined?
Emory University Logo Guidelines
-
Abstract Priority Queue
4
public abstract class AbstractPriorityQueue<T extends Comparable<T>>
{
...
abstract public void add(T key);
abstract protected T removeAux();
abstract public int size();
public boolean isEmpty()
{
return size() == 0;
}
public T remove()
{
if (isEmpty()) throw new NoSuchElementException("No key exists.");
return removeAux();
}
}
abstract
methods
defined?
exception handling
Emory University Logo Guidelines
-
Lazy Priority Queue
5
Emory University Logo Guidelines
-
Lazy Priority Queue
5
Add: insert each key to the back of the list.
Emory University Logo Guidelines
-
Lazy Priority Queue
5
Add: insert each key to the back of the list.
Remove: find the key with the priority, and remove it from the list.
Emory University Logo Guidelines
-
Lazy Priority Queue
5
Add: insert each key to the back of the list.
Remove: find the key with the priority, and remove it from the list.
public class LazyPriorityQueue<T extends Comparable<T>>

extends AbstractPriorityQueue<T>
{
private List<T> keys;
public LazyPriorityQueue()
{
this(Comparator.naturalOrder());
}
public LazyPriorityQueue(Comparator<T> comparator)
{
super(comparator);
keys = new ArrayList<>();
}
Emory University Logo Guidelines
-
Lazy Priority Queue
5
Add: insert each key to the back of the list.
Remove: find the key with the priority, and remove it from the list.
public class LazyPriorityQueue<T extends Comparable<T>>

extends AbstractPriorityQueue<T>
{
private List<T> keys;
public LazyPriorityQueue()
{
this(Comparator.naturalOrder());
}
public LazyPriorityQueue(Comparator<T> comparator)
{
super(comparator);
keys = new ArrayList<>();
}
Emory University Logo Guidelines
-
Lazy Priority Queue
5
Add: insert each key to the back of the list.
Remove: find the key with the priority, and remove it from the list.
public class LazyPriorityQueue<T extends Comparable<T>>

extends AbstractPriorityQueue<T>
{
private List<T> keys;
public LazyPriorityQueue()
{
this(Comparator.naturalOrder());
}
public LazyPriorityQueue(Comparator<T> comparator)
{
super(comparator);
keys = new ArrayList<>();
}
calls?
Emory University Logo Guidelines
-
Lazy Priority Queue
6
@Override
public int size()
{
return keys.size();
}
@Override
public void add(T key)
{
keys.add(key);
}
@Override
protected T removeAux()
{
T max = Collections.max(keys, comparator);
keys.remove(max);
return max;
}
Emory University Logo Guidelines
-
Lazy Priority Queue
6
@Override
public int size()
{
return keys.size();
}
@Override
public void add(T key)
{
keys.add(key);
}
@Override
protected T removeAux()
{
T max = Collections.max(keys, comparator);
keys.remove(max);
return max;
}
annotation
Emory University Logo Guidelines
-
Lazy Priority Queue
6
@Override
public int size()
{
return keys.size();
}
@Override
public void add(T key)
{
keys.add(key);
}
@Override
protected T removeAux()
{
T max = Collections.max(keys, comparator);
keys.remove(max);
return max;
}
annotation
complexity?
Emory University Logo Guidelines
-
Lazy Priority Queue
6
@Override
public int size()
{
return keys.size();
}
@Override
public void add(T key)
{
keys.add(key);
}
@Override
protected T removeAux()
{
T max = Collections.max(keys, comparator);
keys.remove(max);
return max;
}
annotation
complexity?
built-in method
https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html
Emory University Logo Guidelines
-
Lazy Priority Queue
6
@Override
public int size()
{
return keys.size();
}
@Override
public void add(T key)
{
keys.add(key);
}
@Override
protected T removeAux()
{
T max = Collections.max(keys, comparator);
keys.remove(max);
return max;
}
annotation
complexity?
complexity?
built-in method
https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html
Emory University Logo Guidelines
-
Eager Priority Queue
7
Emory University Logo Guidelines
-
Eager Priority Queue
7
Add: insert each key to the list according to the priority.
Emory University Logo Guidelines
-
Eager Priority Queue
7
Add: insert each key to the list according to the priority.
Remove: remove the last key in the list.
Emory University Logo Guidelines
-
Eager Priority Queue
7
Add: insert each key to the list according to the priority.
Remove: remove the last key in the list.
@Override
public void add(T key)
{
int index = Collections.binarySearch(keys, key, comparator);
if (index < 0) index = -(index + 1);
keys.add(index, key);
}
@Override
protected T removeAux()
{
return keys.remove(keys.size()-1);
}
Emory University Logo Guidelines
-
Eager Priority Queue
7
Add: insert each key to the list according to the priority.
Remove: remove the last key in the list.
@Override
public void add(T key)
{
int index = Collections.binarySearch(keys, key, comparator);
if (index < 0) index = -(index + 1);
keys.add(index, key);
}
@Override
protected T removeAux()
{
return keys.remove(keys.size()-1);
}
https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html
Emory University Logo Guidelines
-
Eager Priority Queue
7
Add: insert each key to the list according to the priority.
Remove: remove the last key in the list.
@Override
public void add(T key)
{
int index = Collections.binarySearch(keys, key, comparator);
if (index < 0) index = -(index + 1);
keys.add(index, key);
}
@Override
protected T removeAux()
{
return keys.remove(keys.size()-1);
}
https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html
complexity?
Emory University Logo Guidelines
-
Eager Priority Queue
7
Add: insert each key to the list according to the priority.
Remove: remove the last key in the list.
@Override
public void add(T key)
{
int index = Collections.binarySearch(keys, key, comparator);
if (index < 0) index = -(index + 1);
keys.add(index, key);
}
@Override
protected T removeAux()
{
return keys.remove(keys.size()-1);
}
https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html
complexity?
complexity?
Emory University Logo Guidelines
-
Binary Heap
8
Emory University Logo Guidelines
-
Binary Heap
• What is a heap?
8
Emory University Logo Guidelines
-
Binary Heap
• What is a heap?
- A tree where the key of each node has a higher or equal priority than
its children.
8
Emory University Logo Guidelines
-
Binary Heap
• What is a heap?
- A tree where the key of each node has a higher or equal priority than
its children.
- The tree is guaranteed to be balanced.
8
Emory University Logo Guidelines
-
Binary Heap
• What is a heap?
- A tree where the key of each node has a higher or equal priority than
its children.
- The tree is guaranteed to be balanced.
- What is a binary heap?

8
Emory University Logo Guidelines
-
Binary Heap
• What is a heap?
- A tree where the key of each node has a higher or equal priority than
its children.
- The tree is guaranteed to be balanced.
- What is a binary heap?

• Operations
8
Emory University Logo Guidelines
-
Binary Heap
• What is a heap?
- A tree where the key of each node has a higher or equal priority than
its children.
- The tree is guaranteed to be balanced.
- What is a binary heap?

• Operations
- Add: swim.
8
Emory University Logo Guidelines
-
Binary Heap
• What is a heap?
- A tree where the key of each node has a higher or equal priority than
its children.
- The tree is guaranteed to be balanced.
- What is a binary heap?

• Operations
- Add: swim.
- Remove: sink.
8
Emory University Logo Guidelines
-
Binary Heap
• What is a heap?
- A tree where the key of each node has a higher or equal priority than
its children.
- The tree is guaranteed to be balanced.
- What is a binary heap?

• Operations
- Add: swim.
- Remove: sink.
- Both operations can be done in O(log n).
8
Emory University Logo Guidelines
-
Binary Heap
9
Emory University Logo Guidelines
-
Binary Heap
9
7 3 2 4 6 1 5Input =
Emory University Logo Guidelines
-
Binary Heap
9
7 3 2 4 6 1 5Input =
7
6 5
3 4 1 2
Emory University Logo Guidelines
-
Binary Heap
9
7 3 2 4 6 1 5Input =
7
6 5
3 4 1 2
∅ 7 6 5 3 4 1 2list =
Emory University Logo Guidelines
-
Binary Heap
9
7 3 2 4 6 1 5Input =
7
6 5
3 4 1 2
∅ 7 6 5 3 4 1 2list =
Why?
Emory University Logo Guidelines
-
Binary Heap
9
7 3 2 4 6 1 5Input =
7
6 5
3 4 1 2
∅ 7 6 5 3 4 1 2list =
Index of the parent?
Why?
Emory University Logo Guidelines
-
Binary Heap
9
7 3 2 4 6 1 5Input =
7
6 5
3 4 1 2
∅ 7 6 5 3 4 1 2list =
Index of the parent?
k/2
Why?
Emory University Logo Guidelines
-
Binary Heap
9
7 3 2 4 6 1 5Input =
7
6 5
3 4 1 2
∅ 7 6 5 3 4 1 2list =
Index of the parent?
Index of the children?
k/2
Why?
Emory University Logo Guidelines
-
Binary Heap
9
7 3 2 4 6 1 5Input =
7
6 5
3 4 1 2
∅ 7 6 5 3 4 1 2list =
Index of the parent?
Index of the children?
k/2
k*2, k*2 + 1
Why?
Emory University Logo Guidelines
-
public class BinaryHeap<T extends Comparable<T>> extends AbstractPriorityQueue<T>
{
private List<T> keys;
private int size;
public BinaryHeap(Comparator<T> comparator)
{
super(comparator);
keys = new ArrayList<>();
keys.add(null);
size = 0;
}
@Override
public int size()
{
return size;
}
Binary Heap
10
Emory University Logo Guidelines
-
public class BinaryHeap<T extends Comparable<T>> extends AbstractPriorityQueue<T>
{
private List<T> keys;
private int size;
public BinaryHeap(Comparator<T> comparator)
{
super(comparator);
keys = new ArrayList<>();
keys.add(null);
size = 0;
}
@Override
public int size()
{
return size;
}
Binary Heap
10
Emory University Logo Guidelines
-
public class BinaryHeap<T extends Comparable<T>> extends AbstractPriorityQueue<T>
{
private List<T> keys;
private int size;
public BinaryHeap(Comparator<T> comparator)
{
super(comparator);
keys = new ArrayList<>();
keys.add(null);
size = 0;
}
@Override
public int size()
{
return size;
}
Binary Heap
10
initialize the first item as null
Emory University Logo Guidelines
-
Binary Heap - Add (Swim)
11
7 3 2 4 6 1 5
Emory University Logo Guidelines
-
Binary Heap - Add (Swim)
11
7 3 2 4 6 1 5
Add each key to the end of the list.
Swim until it becomes a heap.
Emory University Logo Guidelines
-
Binary Heap - Add (Swim)
11
7 3 2 4 6 1 5
Add each key to the end of the list.
Swim until it becomes a heap.
Emory University Logo Guidelines
-
Binary Heap - Add (Swim)
11
7 3 2 4 6 1 5
7
Add each key to the end of the list.
Swim until it becomes a heap.
Emory University Logo Guidelines
-
Binary Heap - Add (Swim)
11
7 3 2 4 6 1 5
7
Add each key to the end of the list.
Swim until it becomes a heap.
Emory University Logo Guidelines
-
Binary Heap - Add (Swim)
11
7 3 2 4 6 1 5
7
3
Add each key to the end of the list.
Swim until it becomes a heap.
Emory University Logo Guidelines
-
Binary Heap - Add (Swim)
11
7 3 2 4 6 1 5
7
3
Add each key to the end of the list.
Swim until it becomes a heap.
Emory University Logo Guidelines
-
Binary Heap - Add (Swim)
11
7 3 2 4 6 1 5
7
3 2
Add each key to the end of the list.
Swim until it becomes a heap.
Emory University Logo Guidelines
-
Binary Heap - Add (Swim)
11
7 3 2 4 6 1 5
7
3 2
Add each key to the end of the list.
Swim until it becomes a heap.
Emory University Logo Guidelines
-
Binary Heap - Add (Swim)
11
7 3 2 4 6 1 5
7
3 2
4
Add each key to the end of the list.
Swim until it becomes a heap.
Emory University Logo Guidelines
-
Binary Heap - Add (Swim)
11
7 3 2 4 6 1 5
7
3 2
4
Add each key to the end of the list.
Swim until it becomes a heap.
4
3
Emory University Logo Guidelines
-
Binary Heap - Add (Swim)
11
7 3 2 4 6 1 5
7
3 2
4
Add each key to the end of the list.
Swim until it becomes a heap.
4
3
Emory University Logo Guidelines
-
Binary Heap - Add (Swim)
11
7 3 2 4 6 1 5
7
3 2
4 6
Add each key to the end of the list.
Swim until it becomes a heap.
4
3
Emory University Logo Guidelines
-
Binary Heap - Add (Swim)
11
7 3 2 4 6 1 5
7
3 2
4 6
Add each key to the end of the list.
Swim until it becomes a heap.
4
3
6
4
Emory University Logo Guidelines
-
Binary Heap - Add (Swim)
11
7 3 2 4 6 1 5
7
3 2
4 6
Add each key to the end of the list.
Swim until it becomes a heap.
4
3
6
4
Emory University Logo Guidelines
-
Binary Heap - Add (Swim)
11
7 3 2 4 6 1 5
7
3 2
4 6 1
Add each key to the end of the list.
Swim until it becomes a heap.
4
3
6
4
Emory University Logo Guidelines
-
Binary Heap - Add (Swim)
11
7 3 2 4 6 1 5
7
3 2
4 6 1
Add each key to the end of the list.
Swim until it becomes a heap.
4
3
6
4
Emory University Logo Guidelines
-
Binary Heap - Add (Swim)
11
7 3 2 4 6 1 5
7
3 2
4 6 1 5
Add each key to the end of the list.
Swim until it becomes a heap.
4
3
6
4
Emory University Logo Guidelines
-
Binary Heap - Add (Swim)
11
7 3 2 4 6 1 5
7
3 2
4 6 1 5
Add each key to the end of the list.
Swim until it becomes a heap.
4
3
6
4
5
2
Emory University Logo Guidelines
-
Binary Heap - Add (Swim)
11
7 3 2 4 6 1 5
7
3 2
4 6 1 5
Add each key to the end of the list.
Swim until it becomes a heap.
4
3
6
4
5
2
Emory University Logo Guidelines
-
Binary Heap - Add (Swim)
11
7 3 2 4 6 1 5
7
3 2
4 6 1 5
Add each key to the end of the list.
Swim until it becomes a heap.
4
3
6
4
5
2
Complexity?
Emory University Logo Guidelines
-
Binary Heap - Add (Swim)
12
@Override
public void add(T key)
{
keys.add(key);
swim(++size);
}
private void swim(int k)
{
while (k > 1 && comparator.compare(keys.get(k/2), keys.get(k)) < 0)
{
Collections.swap(keys, k/2, k);
k /= 2;
}
}
Emory University Logo Guidelines
-
Binary Heap - Add (Swim)
12
@Override
public void add(T key)
{
keys.add(key);
swim(++size);
}
private void swim(int k)
{
while (k > 1 && comparator.compare(keys.get(k/2), keys.get(k)) < 0)
{
Collections.swap(keys, k/2, k);
k /= 2;
}
}
Emory University Logo Guidelines
-
Binary Heap - Add (Swim)
12
@Override
public void add(T key)
{
keys.add(key);
swim(++size);
}
private void swim(int k)
{
while (k > 1 && comparator.compare(keys.get(k/2), keys.get(k)) < 0)
{
Collections.swap(keys, k/2, k);
k /= 2;
}
}
Emory University Logo Guidelines
-
Binary Heap - Add (Swim)
12
@Override
public void add(T key)
{
keys.add(key);
swim(++size);
}
private void swim(int k)
{
while (k > 1 && comparator.compare(keys.get(k/2), keys.get(k)) < 0)
{
Collections.swap(keys, k/2, k);
k /= 2;
}
}
parent
Emory University Logo Guidelines
-
Binary Heap - Remove (Sink)
13
Emory University Logo Guidelines
-
Binary Heap - Remove (Sink)
13
Replace the root with the last key in the list.
Sink until it becomes a heap.
Emory University Logo Guidelines
-
Binary Heap - Remove (Sink)
13
7
6 5
3 4 1 2
Replace the root with the last key in the list.
Sink until it becomes a heap.
Emory University Logo Guidelines
-
Binary Heap - Remove (Sink)
13
7
6 5
3 4 1 2
Replace the root with the last key in the list.
Sink until it becomes a heap.
Emory University Logo Guidelines
-
Binary Heap - Remove (Sink)
13
7
6 5
3 4 1
2
Replace the root with the last key in the list.
Sink until it becomes a heap.
Emory University Logo Guidelines
-
Binary Heap - Remove (Sink)
13
7
6 5
3 4 1
26
2
Replace the root with the last key in the list.
Sink until it becomes a heap.
Emory University Logo Guidelines
-
Binary Heap - Remove (Sink)
13
7
6 5
3 4 1
26
24
2
Replace the root with the last key in the list.
Sink until it becomes a heap.
Emory University Logo Guidelines
-
Binary Heap - Remove (Sink)
13
7
6 5
3 4 1
26
24
2
Replace the root with the last key in the list.
Sink until it becomes a heap.
Emory University Logo Guidelines
-
Binary Heap - Remove (Sink)
13
7
6 5
3 4
26
24
2
1
Replace the root with the last key in the list.
Sink until it becomes a heap.
Emory University Logo Guidelines
-
Binary Heap - Remove (Sink)
13
7
6 5
3 4
26
24
2
15
1
Replace the root with the last key in the list.
Sink until it becomes a heap.
Emory University Logo Guidelines
-
Binary Heap - Remove (Sink)
13
7
6 5
3 4
26
24
2
15
1
Replace the root with the last key in the list.
Sink until it becomes a heap.
Emory University Logo Guidelines
-
14
@Override
protected T removeAux()
{
Collections.swap(keys, 1, size);
T max = keys.remove(size--);
sink(1);
return max;
}
private void sink(int k)
{
for (int i=k*2; i<=size; k=i,i*=2)
{
if (i < size && comparator.compare(keys.get(i), keys.get(i+1)) < 0) i++;
if (comparator.compare(keys.get(k), keys.get(i)) >= 0) break;
Collections.swap(keys, k, i);
}
}
Binary Heap - Remove (Sink)
Emory University Logo Guidelines
-
14
@Override
protected T removeAux()
{
Collections.swap(keys, 1, size);
T max = keys.remove(size--);
sink(1);
return max;
}
private void sink(int k)
{
for (int i=k*2; i<=size; k=i,i*=2)
{
if (i < size && comparator.compare(keys.get(i), keys.get(i+1)) < 0) i++;
if (comparator.compare(keys.get(k), keys.get(i)) >= 0) break;
Collections.swap(keys, k, i);
}
}
root
Binary Heap - Remove (Sink)
Emory University Logo Guidelines
-
14
@Override
protected T removeAux()
{
Collections.swap(keys, 1, size);
T max = keys.remove(size--);
sink(1);
return max;
}
private void sink(int k)
{
for (int i=k*2; i<=size; k=i,i*=2)
{
if (i < size && comparator.compare(keys.get(i), keys.get(i+1)) < 0) i++;
if (comparator.compare(keys.get(k), keys.get(i)) >= 0) break;
Collections.swap(keys, k, i);
}
}
root
left child
Binary Heap - Remove (Sink)
Emory University Logo Guidelines
-
14
@Override
protected T removeAux()
{
Collections.swap(keys, 1, size);
T max = keys.remove(size--);
sink(1);
return max;
}
private void sink(int k)
{
for (int i=k*2; i<=size; k=i,i*=2)
{
if (i < size && comparator.compare(keys.get(i), keys.get(i+1)) < 0) i++;
if (comparator.compare(keys.get(k), keys.get(i)) >= 0) break;
Collections.swap(keys, k, i);
}
}
root
left child
between children
Binary Heap - Remove (Sink)
Emory University Logo Guidelines
-
Unit Test - Accuracy
15
void testAccuracy(AbstractPriorityQueue<Integer> q, Comparator<Integer> sort)
{
List<Integer> keys = DSUtils.toIntegerList(4,1,3,2,5,6,8,3,4,7,5,9,7);
keys.forEach(key -> q.add(key));
Collections.sort(keys, sort);
keys.forEach(key -> assertEquals(key, q.removeAux()));
}
@Test
public void testAccuracy()
{
testAccuracy(new LazyPriorityQueue<>() , Comparator.reverseOrder());
testAccuracy(new EagerPriorityQueue<>(), Comparator.reverseOrder());
testAccuracy(new BinaryHeap<>() , Comparator.reverseOrder());
testAccuracy(new LazyPriorityQueue<Integer> (Comparator.reverseOrder()), Comparator.naturalOrder());
testAccuracy(new EagerPriorityQueue<Integer>(Comparator.reverseOrder()), Comparator.naturalOrder());
testAccuracy(new BinaryHeap<Integer> (Comparator.reverseOrder()), Comparator.naturalOrder());
}
Emory University Logo Guidelines
-
Unit Test - Accuracy
15
void testAccuracy(AbstractPriorityQueue<Integer> q, Comparator<Integer> sort)
{
List<Integer> keys = DSUtils.toIntegerList(4,1,3,2,5,6,8,3,4,7,5,9,7);
keys.forEach(key -> q.add(key));
Collections.sort(keys, sort);
keys.forEach(key -> assertEquals(key, q.removeAux()));
}
@Test
public void testAccuracy()
{
testAccuracy(new LazyPriorityQueue<>() , Comparator.reverseOrder());
testAccuracy(new EagerPriorityQueue<>(), Comparator.reverseOrder());
testAccuracy(new BinaryHeap<>() , Comparator.reverseOrder());
testAccuracy(new LazyPriorityQueue<Integer> (Comparator.reverseOrder()), Comparator.naturalOrder());
testAccuracy(new EagerPriorityQueue<Integer>(Comparator.reverseOrder()), Comparator.naturalOrder());
testAccuracy(new BinaryHeap<Integer> (Comparator.reverseOrder()), Comparator.naturalOrder());
}
Emory University Logo Guidelines
-
Unit Test - Accuracy
15
void testAccuracy(AbstractPriorityQueue<Integer> q, Comparator<Integer> sort)
{
List<Integer> keys = DSUtils.toIntegerList(4,1,3,2,5,6,8,3,4,7,5,9,7);
keys.forEach(key -> q.add(key));
Collections.sort(keys, sort);
keys.forEach(key -> assertEquals(key, q.removeAux()));
}
unit test
@Test
public void testAccuracy()
{
testAccuracy(new LazyPriorityQueue<>() , Comparator.reverseOrder());
testAccuracy(new EagerPriorityQueue<>(), Comparator.reverseOrder());
testAccuracy(new BinaryHeap<>() , Comparator.reverseOrder());
testAccuracy(new LazyPriorityQueue<Integer> (Comparator.reverseOrder()), Comparator.naturalOrder());
testAccuracy(new EagerPriorityQueue<Integer>(Comparator.reverseOrder()), Comparator.naturalOrder());
testAccuracy(new BinaryHeap<Integer> (Comparator.reverseOrder()), Comparator.naturalOrder());
}
Emory University Logo Guidelines
-
Unit Test - Speed
16
Emory University Logo Guidelines
-
Unit Test - Speed
• If you want to see if your program runs as fast as it should,
16
Emory University Logo Guidelines
-
Unit Test - Speed
• If you want to see if your program runs as fast as it should,
- The best way is using a profiler (e.g., JProfiler).
16
Emory University Logo Guidelines
-
Unit Test - Speed
• If you want to see if your program runs as fast as it should,
- The best way is using a profiler (e.g., JProfiler).
- The easiest way is measuring the time between operations.
16
Emory University Logo Guidelines
-
Unit Test - Speed
• If you want to see if your program runs as fast as it should,
- The best way is using a profiler (e.g., JProfiler).
- The easiest way is measuring the time between operations.
16
<T extends Comparable<T>>long getRuntime(int warm, int iter, AbstractPriorityQueue<T> q)
{
long st, et;
for (int i=0; i<warm; i++)
q.remove();
st = System.currentTimeMillis();
for (int i=0; i<iter; i++)
q.remove();
et = System.currentTimeMillis();
return et - st;
}
Emory University Logo Guidelines
-
Unit Test - Speed
• If you want to see if your program runs as fast as it should,
- The best way is using a profiler (e.g., JProfiler).
- The easiest way is measuring the time between operations.
16
<T extends Comparable<T>>long getRuntime(int warm, int iter, AbstractPriorityQueue<T> q)
{
long st, et;
for (int i=0; i<warm; i++)
q.remove();
st = System.currentTimeMillis();
for (int i=0; i<iter; i++)
q.remove();
et = System.currentTimeMillis();
return et - st;
}
warm-up
Emory University Logo Guidelines
-
Unit Test - Speed
• If you want to see if your program runs as fast as it should,
- The best way is using a profiler (e.g., JProfiler).
- The easiest way is measuring the time between operations.
16
<T extends Comparable<T>>long getRuntime(int warm, int iter, AbstractPriorityQueue<T> q)
{
long st, et;
for (int i=0; i<warm; i++)
q.remove();
st = System.currentTimeMillis();
for (int i=0; i<iter; i++)
q.remove();
et = System.currentTimeMillis();
return et - st;
}
warm-up
operation
Emory University Logo Guidelines
-
Speed Comparison - Add
17
Milliseconds
0
150
300
450
600
Queue sizes
100 200 300 400 500 600 700 800 900 1000
Lazy Eager Heap
Emory University Logo Guidelines
-
Speed Comparison - Add
17
Milliseconds
0
150
300
450
600
Queue sizes
100 200 300 400 500 600 700 800 900 1000
Lazy Eager Heap
O(1)
Emory University Logo Guidelines
-
Speed Comparison - Add
17
Milliseconds
0
150
300
450
600
Queue sizes
100 200 300 400 500 600 700 800 900 1000
Lazy Eager Heap
Both O(log n)?O(1)
Emory University Logo Guidelines
-
Speed Comparison - Remove
18
Milliseconds
0
1000
2000
3000
4000
Queue sizes
100 200 300 400 500 600 700 800 900 1000
Lazy Eager Heap
Emory University Logo Guidelines
-
Speed Comparison - Remove
18
Milliseconds
0
1000
2000
3000
4000
Queue sizes
100 200 300 400 500 600 700 800 900 1000
Lazy Eager Heap
O(1)
Emory University Logo Guidelines
-
Speed Comparison - Remove
18
Milliseconds
0
1000
2000
3000
4000
Queue sizes
100 200 300 400 500 600 700 800 900 1000
Lazy Eager Heap
O(1) O(log n)
Emory University Logo Guidelines
-
Speed Comparison - Remove
18
Milliseconds
0
1000
2000
3000
4000
Queue sizes
100 200 300 400 500 600 700 800 900 1000
Lazy Eager Heap
O(n) O(1) O(log n)
Emory University Logo Guidelines
-
Agenda
• Exercise
- https://github.com/emory-courses/cs323/wiki/Priority-Queues
• Reading
- https://en.wikipedia.org/wiki/Selection_sort
- https://en.wikipedia.org/wiki/Insertion_sort
- https://en.wikipedia.org/wiki/Heapsort
- https://en.wikipedia.org/wiki/Shellsort
19

More Related Content

PDF
CS323: Sort - Divide and Conquer
PDF
CS323: Sort - Distribution-based
PDF
CS323: Trie
PDF
CS323: Sort - Comparison-based
PDF
CS323: Minimum Spanning Trees - Undirected
PDF
CS323: Dynamic Programming
PDF
CS323: Balanced Binary Search Trees
PDF
CS323: Binary Search Trees
CS323: Sort - Divide and Conquer
CS323: Sort - Distribution-based
CS323: Trie
CS323: Sort - Comparison-based
CS323: Minimum Spanning Trees - Undirected
CS323: Dynamic Programming
CS323: Balanced Binary Search Trees
CS323: Binary Search Trees

What's hot (9)

PDF
CS323: Longest Common Subsequences
PPT
09 logic programming
PDF
Declare Your Language: Type Checking
PDF
Declare Your Language: Name Resolution
PDF
Declare Your Language: Transformation by Strategic Term Rewriting
PDF
Numeric Range Queries in Lucene and Solr
PPTX
L04 Software Design 2
PPTX
Category theory for beginners
CS323: Longest Common Subsequences
09 logic programming
Declare Your Language: Type Checking
Declare Your Language: Name Resolution
Declare Your Language: Transformation by Strategic Term Rewriting
Numeric Range Queries in Lucene and Solr
L04 Software Design 2
Category theory for beginners
Ad

Similar to CS323: Priority Queues (9)

PDF
PriorityQueue.cs Jim Mischel using System; using Sy.pdf
PPT
Priority queues
PDF
computer notes - Priority queue
DOCX
EmptyCollectionException-java -- - Represents the situation in which.docx
PDF
5.1 Priority Queues.pdf 5.1 Priority Queues.pdf5.1 Priority Queues.pdf5.1 Pri...
PDF
Chapter11
DOCX
I need help with implementing the priority queue data structure with a.docx
DOCX
package algs13;import stdlib.;import java.util.Iterator;im.docx
PDF
Priorty queue
PriorityQueue.cs Jim Mischel using System; using Sy.pdf
Priority queues
computer notes - Priority queue
EmptyCollectionException-java -- - Represents the situation in which.docx
5.1 Priority Queues.pdf 5.1 Priority Queues.pdf5.1 Priority Queues.pdf5.1 Pri...
Chapter11
I need help with implementing the priority queue data structure with a.docx
package algs13;import stdlib.;import java.util.Iterator;im.docx
Priorty queue
Ad

More from Jinho Choi (20)

PDF
Adaptation of Multilingual Transformer Encoder for Robust Enhanced Universal ...
PDF
Analysis of Hierarchical Multi-Content Text Classification Model on B-SHARP D...
PDF
Competence-Level Prediction and Resume & Job Description Matching Using Conte...
PDF
Transformers to Learn Hierarchical Contexts in Multiparty Dialogue for Span-b...
PDF
The Myth of Higher-Order Inference in Coreference Resolution
PDF
Noise Pollution in Hospital Readmission Prediction: Long Document Classificat...
PDF
Abstract Meaning Representation
PDF
Semantic Role Labeling
PDF
CKY Parsing
PDF
CS329 - WordNet Similarities
PDF
CS329 - Lexical Relations
PDF
Automatic Knowledge Base Expansion for Dialogue Management
PDF
Attention is All You Need for AMR Parsing
PDF
Graph-to-Text Generation and its Applications to Dialogue
PDF
Real-time Coreference Resolution for Dialogue Understanding
PDF
Topological Sort
PDF
Tries - Put
PDF
Multi-modal Embedding Learning for Early Detection of Alzheimer's Disease
PDF
Building Widely-Interpretable Semantic Networks for Dialogue Contexts
PDF
How to make Emora talk about Sports Intelligently
Adaptation of Multilingual Transformer Encoder for Robust Enhanced Universal ...
Analysis of Hierarchical Multi-Content Text Classification Model on B-SHARP D...
Competence-Level Prediction and Resume & Job Description Matching Using Conte...
Transformers to Learn Hierarchical Contexts in Multiparty Dialogue for Span-b...
The Myth of Higher-Order Inference in Coreference Resolution
Noise Pollution in Hospital Readmission Prediction: Long Document Classificat...
Abstract Meaning Representation
Semantic Role Labeling
CKY Parsing
CS329 - WordNet Similarities
CS329 - Lexical Relations
Automatic Knowledge Base Expansion for Dialogue Management
Attention is All You Need for AMR Parsing
Graph-to-Text Generation and its Applications to Dialogue
Real-time Coreference Resolution for Dialogue Understanding
Topological Sort
Tries - Put
Multi-modal Embedding Learning for Early Detection of Alzheimer's Disease
Building Widely-Interpretable Semantic Networks for Dialogue Contexts
How to make Emora talk about Sports Intelligently

Recently uploaded (20)

PDF
MIND Revenue Release Quarter 2 2025 Press Release
PDF
Unlocking AI with Model Context Protocol (MCP)
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PPTX
Understanding_Digital_Forensics_Presentation.pptx
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PPTX
Big Data Technologies - Introduction.pptx
PDF
Encapsulation theory and applications.pdf
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
KodekX | Application Modernization Development
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Approach and Philosophy of On baking technology
PPTX
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
MIND Revenue Release Quarter 2 2025 Press Release
Unlocking AI with Model Context Protocol (MCP)
“AI and Expert System Decision Support & Business Intelligence Systems”
Understanding_Digital_Forensics_Presentation.pptx
The AUB Centre for AI in Media Proposal.docx
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Mobile App Security Testing_ A Comprehensive Guide.pdf
Big Data Technologies - Introduction.pptx
Encapsulation theory and applications.pdf
Dropbox Q2 2025 Financial Results & Investor Presentation
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
KodekX | Application Modernization Development
The Rise and Fall of 3GPP – Time for a Sabbatical?
Approach and Philosophy of On baking technology
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
MYSQL Presentation for SQL database connectivity
Diabetes mellitus diagnosis method based random forest with bat algorithm
Building Integrated photovoltaic BIPV_UPV.pdf

CS323: Priority Queues

  • 1. Emory University Logo Guidelines - Priority Queues Data Structures and Algorithms Emory University Jinho D. Choi
  • 2. Emory University Logo Guidelines - Priority Queue 2
  • 3. Emory University Logo Guidelines - Priority Queue • Priority queue 2
  • 4. Emory University Logo Guidelines - Priority Queue • Priority queue - Add: insert a comparable key. 2
  • 5. Emory University Logo Guidelines - Priority Queue • Priority queue - Add: insert a comparable key. - Remove: find and remove the key with the highest priority. 2
  • 6. Emory University Logo Guidelines - Priority Queue • Priority queue - Add: insert a comparable key. - Remove: find and remove the key with the highest priority. • Application 2
  • 7. Emory University Logo Guidelines - Priority Queue • Priority queue - Add: insert a comparable key. - Remove: find and remove the key with the highest priority. • Application - Scheduling. 2
  • 8. Emory University Logo Guidelines - Priority Queue • Priority queue - Add: insert a comparable key. - Remove: find and remove the key with the highest priority. • Application - Scheduling. • Implementation 2
  • 9. Emory University Logo Guidelines - Priority Queue • Priority queue - Add: insert a comparable key. - Remove: find and remove the key with the highest priority. • Application - Scheduling. • Implementation - Lazy vs. Eager. 2
  • 10. Emory University Logo Guidelines - Priority Queue • Priority queue - Add: insert a comparable key. - Remove: find and remove the key with the highest priority. • Application - Scheduling. • Implementation - Lazy vs. Eager. - Heap. 2
  • 11. Emory University Logo Guidelines - Abstract Priority Queue 3 public abstract class AbstractPriorityQueue<T extends Comparable<T>> { protected Comparator<T> comparator; public AbstractPriorityQueue(Comparator<T> comparator) { this.comparator = comparator; } ... }
  • 12. Emory University Logo Guidelines - Abstract Priority Queue 3 public abstract class AbstractPriorityQueue<T extends Comparable<T>> { protected Comparator<T> comparator; public AbstractPriorityQueue(Comparator<T> comparator) { this.comparator = comparator; } ... }
  • 13. Emory University Logo Guidelines - Abstract Priority Queue 3 public abstract class AbstractPriorityQueue<T extends Comparable<T>> { protected Comparator<T> comparator; public AbstractPriorityQueue(Comparator<T> comparator) { this.comparator = comparator; } ... } class?
  • 14. Emory University Logo Guidelines - Abstract Priority Queue 3 public abstract class AbstractPriorityQueue<T extends Comparable<T>> { protected Comparator<T> comparator; public AbstractPriorityQueue(Comparator<T> comparator) { this.comparator = comparator; } ... } class? interface?
  • 15. Emory University Logo Guidelines - Abstract Priority Queue 3 public abstract class AbstractPriorityQueue<T extends Comparable<T>> { protected Comparator<T> comparator; public AbstractPriorityQueue(Comparator<T> comparator) { this.comparator = comparator; } ... } class? genericinterface?
  • 16. Emory University Logo Guidelines - Abstract Priority Queue 3 public abstract class AbstractPriorityQueue<T extends Comparable<T>> { protected Comparator<T> comparator; public AbstractPriorityQueue(Comparator<T> comparator) { this.comparator = comparator; } ... } class? genericinterface?
  • 17. Emory University Logo Guidelines - Abstract Priority Queue 3 public abstract class AbstractPriorityQueue<T extends Comparable<T>> { protected Comparator<T> comparator; public AbstractPriorityQueue(Comparator<T> comparator) { this.comparator = comparator; } ... } class? genericinterface?
  • 18. Emory University Logo Guidelines - Abstract Priority Queue 3 public abstract class AbstractPriorityQueue<T extends Comparable<T>> { protected Comparator<T> comparator; public AbstractPriorityQueue(Comparator<T> comparator) { this.comparator = comparator; } ... } class? genericinterface?
  • 19. Emory University Logo Guidelines - Abstract Priority Queue 3 public abstract class AbstractPriorityQueue<T extends Comparable<T>> { protected Comparator<T> comparator; public AbstractPriorityQueue(Comparator<T> comparator) { this.comparator = comparator; } ... } class? genericinterface?
  • 20. Emory University Logo Guidelines - Abstract Priority Queue 4 public abstract class AbstractPriorityQueue<T extends Comparable<T>> { ... abstract public void add(T key); abstract protected T removeAux(); abstract public int size(); public boolean isEmpty() { return size() == 0; } public T remove() { if (isEmpty()) throw new NoSuchElementException("No key exists."); return removeAux(); } }
  • 21. Emory University Logo Guidelines - Abstract Priority Queue 4 public abstract class AbstractPriorityQueue<T extends Comparable<T>> { ... abstract public void add(T key); abstract protected T removeAux(); abstract public int size(); public boolean isEmpty() { return size() == 0; } public T remove() { if (isEmpty()) throw new NoSuchElementException("No key exists."); return removeAux(); } } abstract methods
  • 22. Emory University Logo Guidelines - Abstract Priority Queue 4 public abstract class AbstractPriorityQueue<T extends Comparable<T>> { ... abstract public void add(T key); abstract protected T removeAux(); abstract public int size(); public boolean isEmpty() { return size() == 0; } public T remove() { if (isEmpty()) throw new NoSuchElementException("No key exists."); return removeAux(); } } abstract methods defined?
  • 23. Emory University Logo Guidelines - Abstract Priority Queue 4 public abstract class AbstractPriorityQueue<T extends Comparable<T>> { ... abstract public void add(T key); abstract protected T removeAux(); abstract public int size(); public boolean isEmpty() { return size() == 0; } public T remove() { if (isEmpty()) throw new NoSuchElementException("No key exists."); return removeAux(); } } abstract methods defined? exception handling
  • 24. Emory University Logo Guidelines - Lazy Priority Queue 5
  • 25. Emory University Logo Guidelines - Lazy Priority Queue 5 Add: insert each key to the back of the list.
  • 26. Emory University Logo Guidelines - Lazy Priority Queue 5 Add: insert each key to the back of the list. Remove: find the key with the priority, and remove it from the list.
  • 27. Emory University Logo Guidelines - Lazy Priority Queue 5 Add: insert each key to the back of the list. Remove: find the key with the priority, and remove it from the list. public class LazyPriorityQueue<T extends Comparable<T>>
 extends AbstractPriorityQueue<T> { private List<T> keys; public LazyPriorityQueue() { this(Comparator.naturalOrder()); } public LazyPriorityQueue(Comparator<T> comparator) { super(comparator); keys = new ArrayList<>(); }
  • 28. Emory University Logo Guidelines - Lazy Priority Queue 5 Add: insert each key to the back of the list. Remove: find the key with the priority, and remove it from the list. public class LazyPriorityQueue<T extends Comparable<T>>
 extends AbstractPriorityQueue<T> { private List<T> keys; public LazyPriorityQueue() { this(Comparator.naturalOrder()); } public LazyPriorityQueue(Comparator<T> comparator) { super(comparator); keys = new ArrayList<>(); }
  • 29. Emory University Logo Guidelines - Lazy Priority Queue 5 Add: insert each key to the back of the list. Remove: find the key with the priority, and remove it from the list. public class LazyPriorityQueue<T extends Comparable<T>>
 extends AbstractPriorityQueue<T> { private List<T> keys; public LazyPriorityQueue() { this(Comparator.naturalOrder()); } public LazyPriorityQueue(Comparator<T> comparator) { super(comparator); keys = new ArrayList<>(); } calls?
  • 30. Emory University Logo Guidelines - Lazy Priority Queue 6 @Override public int size() { return keys.size(); } @Override public void add(T key) { keys.add(key); } @Override protected T removeAux() { T max = Collections.max(keys, comparator); keys.remove(max); return max; }
  • 31. Emory University Logo Guidelines - Lazy Priority Queue 6 @Override public int size() { return keys.size(); } @Override public void add(T key) { keys.add(key); } @Override protected T removeAux() { T max = Collections.max(keys, comparator); keys.remove(max); return max; } annotation
  • 32. Emory University Logo Guidelines - Lazy Priority Queue 6 @Override public int size() { return keys.size(); } @Override public void add(T key) { keys.add(key); } @Override protected T removeAux() { T max = Collections.max(keys, comparator); keys.remove(max); return max; } annotation complexity?
  • 33. Emory University Logo Guidelines - Lazy Priority Queue 6 @Override public int size() { return keys.size(); } @Override public void add(T key) { keys.add(key); } @Override protected T removeAux() { T max = Collections.max(keys, comparator); keys.remove(max); return max; } annotation complexity? built-in method https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html
  • 34. Emory University Logo Guidelines - Lazy Priority Queue 6 @Override public int size() { return keys.size(); } @Override public void add(T key) { keys.add(key); } @Override protected T removeAux() { T max = Collections.max(keys, comparator); keys.remove(max); return max; } annotation complexity? complexity? built-in method https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html
  • 35. Emory University Logo Guidelines - Eager Priority Queue 7
  • 36. Emory University Logo Guidelines - Eager Priority Queue 7 Add: insert each key to the list according to the priority.
  • 37. Emory University Logo Guidelines - Eager Priority Queue 7 Add: insert each key to the list according to the priority. Remove: remove the last key in the list.
  • 38. Emory University Logo Guidelines - Eager Priority Queue 7 Add: insert each key to the list according to the priority. Remove: remove the last key in the list. @Override public void add(T key) { int index = Collections.binarySearch(keys, key, comparator); if (index < 0) index = -(index + 1); keys.add(index, key); } @Override protected T removeAux() { return keys.remove(keys.size()-1); }
  • 39. Emory University Logo Guidelines - Eager Priority Queue 7 Add: insert each key to the list according to the priority. Remove: remove the last key in the list. @Override public void add(T key) { int index = Collections.binarySearch(keys, key, comparator); if (index < 0) index = -(index + 1); keys.add(index, key); } @Override protected T removeAux() { return keys.remove(keys.size()-1); } https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html
  • 40. Emory University Logo Guidelines - Eager Priority Queue 7 Add: insert each key to the list according to the priority. Remove: remove the last key in the list. @Override public void add(T key) { int index = Collections.binarySearch(keys, key, comparator); if (index < 0) index = -(index + 1); keys.add(index, key); } @Override protected T removeAux() { return keys.remove(keys.size()-1); } https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html complexity?
  • 41. Emory University Logo Guidelines - Eager Priority Queue 7 Add: insert each key to the list according to the priority. Remove: remove the last key in the list. @Override public void add(T key) { int index = Collections.binarySearch(keys, key, comparator); if (index < 0) index = -(index + 1); keys.add(index, key); } @Override protected T removeAux() { return keys.remove(keys.size()-1); } https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html complexity? complexity?
  • 42. Emory University Logo Guidelines - Binary Heap 8
  • 43. Emory University Logo Guidelines - Binary Heap • What is a heap? 8
  • 44. Emory University Logo Guidelines - Binary Heap • What is a heap? - A tree where the key of each node has a higher or equal priority than its children. 8
  • 45. Emory University Logo Guidelines - Binary Heap • What is a heap? - A tree where the key of each node has a higher or equal priority than its children. - The tree is guaranteed to be balanced. 8
  • 46. Emory University Logo Guidelines - Binary Heap • What is a heap? - A tree where the key of each node has a higher or equal priority than its children. - The tree is guaranteed to be balanced. - What is a binary heap?
 8
  • 47. Emory University Logo Guidelines - Binary Heap • What is a heap? - A tree where the key of each node has a higher or equal priority than its children. - The tree is guaranteed to be balanced. - What is a binary heap?
 • Operations 8
  • 48. Emory University Logo Guidelines - Binary Heap • What is a heap? - A tree where the key of each node has a higher or equal priority than its children. - The tree is guaranteed to be balanced. - What is a binary heap?
 • Operations - Add: swim. 8
  • 49. Emory University Logo Guidelines - Binary Heap • What is a heap? - A tree where the key of each node has a higher or equal priority than its children. - The tree is guaranteed to be balanced. - What is a binary heap?
 • Operations - Add: swim. - Remove: sink. 8
  • 50. Emory University Logo Guidelines - Binary Heap • What is a heap? - A tree where the key of each node has a higher or equal priority than its children. - The tree is guaranteed to be balanced. - What is a binary heap?
 • Operations - Add: swim. - Remove: sink. - Both operations can be done in O(log n). 8
  • 51. Emory University Logo Guidelines - Binary Heap 9
  • 52. Emory University Logo Guidelines - Binary Heap 9 7 3 2 4 6 1 5Input =
  • 53. Emory University Logo Guidelines - Binary Heap 9 7 3 2 4 6 1 5Input = 7 6 5 3 4 1 2
  • 54. Emory University Logo Guidelines - Binary Heap 9 7 3 2 4 6 1 5Input = 7 6 5 3 4 1 2 ∅ 7 6 5 3 4 1 2list =
  • 55. Emory University Logo Guidelines - Binary Heap 9 7 3 2 4 6 1 5Input = 7 6 5 3 4 1 2 ∅ 7 6 5 3 4 1 2list = Why?
  • 56. Emory University Logo Guidelines - Binary Heap 9 7 3 2 4 6 1 5Input = 7 6 5 3 4 1 2 ∅ 7 6 5 3 4 1 2list = Index of the parent? Why?
  • 57. Emory University Logo Guidelines - Binary Heap 9 7 3 2 4 6 1 5Input = 7 6 5 3 4 1 2 ∅ 7 6 5 3 4 1 2list = Index of the parent? k/2 Why?
  • 58. Emory University Logo Guidelines - Binary Heap 9 7 3 2 4 6 1 5Input = 7 6 5 3 4 1 2 ∅ 7 6 5 3 4 1 2list = Index of the parent? Index of the children? k/2 Why?
  • 59. Emory University Logo Guidelines - Binary Heap 9 7 3 2 4 6 1 5Input = 7 6 5 3 4 1 2 ∅ 7 6 5 3 4 1 2list = Index of the parent? Index of the children? k/2 k*2, k*2 + 1 Why?
  • 60. Emory University Logo Guidelines - public class BinaryHeap<T extends Comparable<T>> extends AbstractPriorityQueue<T> { private List<T> keys; private int size; public BinaryHeap(Comparator<T> comparator) { super(comparator); keys = new ArrayList<>(); keys.add(null); size = 0; } @Override public int size() { return size; } Binary Heap 10
  • 61. Emory University Logo Guidelines - public class BinaryHeap<T extends Comparable<T>> extends AbstractPriorityQueue<T> { private List<T> keys; private int size; public BinaryHeap(Comparator<T> comparator) { super(comparator); keys = new ArrayList<>(); keys.add(null); size = 0; } @Override public int size() { return size; } Binary Heap 10
  • 62. Emory University Logo Guidelines - public class BinaryHeap<T extends Comparable<T>> extends AbstractPriorityQueue<T> { private List<T> keys; private int size; public BinaryHeap(Comparator<T> comparator) { super(comparator); keys = new ArrayList<>(); keys.add(null); size = 0; } @Override public int size() { return size; } Binary Heap 10 initialize the first item as null
  • 63. Emory University Logo Guidelines - Binary Heap - Add (Swim) 11 7 3 2 4 6 1 5
  • 64. Emory University Logo Guidelines - Binary Heap - Add (Swim) 11 7 3 2 4 6 1 5 Add each key to the end of the list. Swim until it becomes a heap.
  • 65. Emory University Logo Guidelines - Binary Heap - Add (Swim) 11 7 3 2 4 6 1 5 Add each key to the end of the list. Swim until it becomes a heap.
  • 66. Emory University Logo Guidelines - Binary Heap - Add (Swim) 11 7 3 2 4 6 1 5 7 Add each key to the end of the list. Swim until it becomes a heap.
  • 67. Emory University Logo Guidelines - Binary Heap - Add (Swim) 11 7 3 2 4 6 1 5 7 Add each key to the end of the list. Swim until it becomes a heap.
  • 68. Emory University Logo Guidelines - Binary Heap - Add (Swim) 11 7 3 2 4 6 1 5 7 3 Add each key to the end of the list. Swim until it becomes a heap.
  • 69. Emory University Logo Guidelines - Binary Heap - Add (Swim) 11 7 3 2 4 6 1 5 7 3 Add each key to the end of the list. Swim until it becomes a heap.
  • 70. Emory University Logo Guidelines - Binary Heap - Add (Swim) 11 7 3 2 4 6 1 5 7 3 2 Add each key to the end of the list. Swim until it becomes a heap.
  • 71. Emory University Logo Guidelines - Binary Heap - Add (Swim) 11 7 3 2 4 6 1 5 7 3 2 Add each key to the end of the list. Swim until it becomes a heap.
  • 72. Emory University Logo Guidelines - Binary Heap - Add (Swim) 11 7 3 2 4 6 1 5 7 3 2 4 Add each key to the end of the list. Swim until it becomes a heap.
  • 73. Emory University Logo Guidelines - Binary Heap - Add (Swim) 11 7 3 2 4 6 1 5 7 3 2 4 Add each key to the end of the list. Swim until it becomes a heap. 4 3
  • 74. Emory University Logo Guidelines - Binary Heap - Add (Swim) 11 7 3 2 4 6 1 5 7 3 2 4 Add each key to the end of the list. Swim until it becomes a heap. 4 3
  • 75. Emory University Logo Guidelines - Binary Heap - Add (Swim) 11 7 3 2 4 6 1 5 7 3 2 4 6 Add each key to the end of the list. Swim until it becomes a heap. 4 3
  • 76. Emory University Logo Guidelines - Binary Heap - Add (Swim) 11 7 3 2 4 6 1 5 7 3 2 4 6 Add each key to the end of the list. Swim until it becomes a heap. 4 3 6 4
  • 77. Emory University Logo Guidelines - Binary Heap - Add (Swim) 11 7 3 2 4 6 1 5 7 3 2 4 6 Add each key to the end of the list. Swim until it becomes a heap. 4 3 6 4
  • 78. Emory University Logo Guidelines - Binary Heap - Add (Swim) 11 7 3 2 4 6 1 5 7 3 2 4 6 1 Add each key to the end of the list. Swim until it becomes a heap. 4 3 6 4
  • 79. Emory University Logo Guidelines - Binary Heap - Add (Swim) 11 7 3 2 4 6 1 5 7 3 2 4 6 1 Add each key to the end of the list. Swim until it becomes a heap. 4 3 6 4
  • 80. Emory University Logo Guidelines - Binary Heap - Add (Swim) 11 7 3 2 4 6 1 5 7 3 2 4 6 1 5 Add each key to the end of the list. Swim until it becomes a heap. 4 3 6 4
  • 81. Emory University Logo Guidelines - Binary Heap - Add (Swim) 11 7 3 2 4 6 1 5 7 3 2 4 6 1 5 Add each key to the end of the list. Swim until it becomes a heap. 4 3 6 4 5 2
  • 82. Emory University Logo Guidelines - Binary Heap - Add (Swim) 11 7 3 2 4 6 1 5 7 3 2 4 6 1 5 Add each key to the end of the list. Swim until it becomes a heap. 4 3 6 4 5 2
  • 83. Emory University Logo Guidelines - Binary Heap - Add (Swim) 11 7 3 2 4 6 1 5 7 3 2 4 6 1 5 Add each key to the end of the list. Swim until it becomes a heap. 4 3 6 4 5 2 Complexity?
  • 84. Emory University Logo Guidelines - Binary Heap - Add (Swim) 12 @Override public void add(T key) { keys.add(key); swim(++size); } private void swim(int k) { while (k > 1 && comparator.compare(keys.get(k/2), keys.get(k)) < 0) { Collections.swap(keys, k/2, k); k /= 2; } }
  • 85. Emory University Logo Guidelines - Binary Heap - Add (Swim) 12 @Override public void add(T key) { keys.add(key); swim(++size); } private void swim(int k) { while (k > 1 && comparator.compare(keys.get(k/2), keys.get(k)) < 0) { Collections.swap(keys, k/2, k); k /= 2; } }
  • 86. Emory University Logo Guidelines - Binary Heap - Add (Swim) 12 @Override public void add(T key) { keys.add(key); swim(++size); } private void swim(int k) { while (k > 1 && comparator.compare(keys.get(k/2), keys.get(k)) < 0) { Collections.swap(keys, k/2, k); k /= 2; } }
  • 87. Emory University Logo Guidelines - Binary Heap - Add (Swim) 12 @Override public void add(T key) { keys.add(key); swim(++size); } private void swim(int k) { while (k > 1 && comparator.compare(keys.get(k/2), keys.get(k)) < 0) { Collections.swap(keys, k/2, k); k /= 2; } } parent
  • 88. Emory University Logo Guidelines - Binary Heap - Remove (Sink) 13
  • 89. Emory University Logo Guidelines - Binary Heap - Remove (Sink) 13 Replace the root with the last key in the list. Sink until it becomes a heap.
  • 90. Emory University Logo Guidelines - Binary Heap - Remove (Sink) 13 7 6 5 3 4 1 2 Replace the root with the last key in the list. Sink until it becomes a heap.
  • 91. Emory University Logo Guidelines - Binary Heap - Remove (Sink) 13 7 6 5 3 4 1 2 Replace the root with the last key in the list. Sink until it becomes a heap.
  • 92. Emory University Logo Guidelines - Binary Heap - Remove (Sink) 13 7 6 5 3 4 1 2 Replace the root with the last key in the list. Sink until it becomes a heap.
  • 93. Emory University Logo Guidelines - Binary Heap - Remove (Sink) 13 7 6 5 3 4 1 26 2 Replace the root with the last key in the list. Sink until it becomes a heap.
  • 94. Emory University Logo Guidelines - Binary Heap - Remove (Sink) 13 7 6 5 3 4 1 26 24 2 Replace the root with the last key in the list. Sink until it becomes a heap.
  • 95. Emory University Logo Guidelines - Binary Heap - Remove (Sink) 13 7 6 5 3 4 1 26 24 2 Replace the root with the last key in the list. Sink until it becomes a heap.
  • 96. Emory University Logo Guidelines - Binary Heap - Remove (Sink) 13 7 6 5 3 4 26 24 2 1 Replace the root with the last key in the list. Sink until it becomes a heap.
  • 97. Emory University Logo Guidelines - Binary Heap - Remove (Sink) 13 7 6 5 3 4 26 24 2 15 1 Replace the root with the last key in the list. Sink until it becomes a heap.
  • 98. Emory University Logo Guidelines - Binary Heap - Remove (Sink) 13 7 6 5 3 4 26 24 2 15 1 Replace the root with the last key in the list. Sink until it becomes a heap.
  • 99. Emory University Logo Guidelines - 14 @Override protected T removeAux() { Collections.swap(keys, 1, size); T max = keys.remove(size--); sink(1); return max; } private void sink(int k) { for (int i=k*2; i<=size; k=i,i*=2) { if (i < size && comparator.compare(keys.get(i), keys.get(i+1)) < 0) i++; if (comparator.compare(keys.get(k), keys.get(i)) >= 0) break; Collections.swap(keys, k, i); } } Binary Heap - Remove (Sink)
  • 100. Emory University Logo Guidelines - 14 @Override protected T removeAux() { Collections.swap(keys, 1, size); T max = keys.remove(size--); sink(1); return max; } private void sink(int k) { for (int i=k*2; i<=size; k=i,i*=2) { if (i < size && comparator.compare(keys.get(i), keys.get(i+1)) < 0) i++; if (comparator.compare(keys.get(k), keys.get(i)) >= 0) break; Collections.swap(keys, k, i); } } root Binary Heap - Remove (Sink)
  • 101. Emory University Logo Guidelines - 14 @Override protected T removeAux() { Collections.swap(keys, 1, size); T max = keys.remove(size--); sink(1); return max; } private void sink(int k) { for (int i=k*2; i<=size; k=i,i*=2) { if (i < size && comparator.compare(keys.get(i), keys.get(i+1)) < 0) i++; if (comparator.compare(keys.get(k), keys.get(i)) >= 0) break; Collections.swap(keys, k, i); } } root left child Binary Heap - Remove (Sink)
  • 102. Emory University Logo Guidelines - 14 @Override protected T removeAux() { Collections.swap(keys, 1, size); T max = keys.remove(size--); sink(1); return max; } private void sink(int k) { for (int i=k*2; i<=size; k=i,i*=2) { if (i < size && comparator.compare(keys.get(i), keys.get(i+1)) < 0) i++; if (comparator.compare(keys.get(k), keys.get(i)) >= 0) break; Collections.swap(keys, k, i); } } root left child between children Binary Heap - Remove (Sink)
  • 103. Emory University Logo Guidelines - Unit Test - Accuracy 15 void testAccuracy(AbstractPriorityQueue<Integer> q, Comparator<Integer> sort) { List<Integer> keys = DSUtils.toIntegerList(4,1,3,2,5,6,8,3,4,7,5,9,7); keys.forEach(key -> q.add(key)); Collections.sort(keys, sort); keys.forEach(key -> assertEquals(key, q.removeAux())); } @Test public void testAccuracy() { testAccuracy(new LazyPriorityQueue<>() , Comparator.reverseOrder()); testAccuracy(new EagerPriorityQueue<>(), Comparator.reverseOrder()); testAccuracy(new BinaryHeap<>() , Comparator.reverseOrder()); testAccuracy(new LazyPriorityQueue<Integer> (Comparator.reverseOrder()), Comparator.naturalOrder()); testAccuracy(new EagerPriorityQueue<Integer>(Comparator.reverseOrder()), Comparator.naturalOrder()); testAccuracy(new BinaryHeap<Integer> (Comparator.reverseOrder()), Comparator.naturalOrder()); }
  • 104. Emory University Logo Guidelines - Unit Test - Accuracy 15 void testAccuracy(AbstractPriorityQueue<Integer> q, Comparator<Integer> sort) { List<Integer> keys = DSUtils.toIntegerList(4,1,3,2,5,6,8,3,4,7,5,9,7); keys.forEach(key -> q.add(key)); Collections.sort(keys, sort); keys.forEach(key -> assertEquals(key, q.removeAux())); } @Test public void testAccuracy() { testAccuracy(new LazyPriorityQueue<>() , Comparator.reverseOrder()); testAccuracy(new EagerPriorityQueue<>(), Comparator.reverseOrder()); testAccuracy(new BinaryHeap<>() , Comparator.reverseOrder()); testAccuracy(new LazyPriorityQueue<Integer> (Comparator.reverseOrder()), Comparator.naturalOrder()); testAccuracy(new EagerPriorityQueue<Integer>(Comparator.reverseOrder()), Comparator.naturalOrder()); testAccuracy(new BinaryHeap<Integer> (Comparator.reverseOrder()), Comparator.naturalOrder()); }
  • 105. Emory University Logo Guidelines - Unit Test - Accuracy 15 void testAccuracy(AbstractPriorityQueue<Integer> q, Comparator<Integer> sort) { List<Integer> keys = DSUtils.toIntegerList(4,1,3,2,5,6,8,3,4,7,5,9,7); keys.forEach(key -> q.add(key)); Collections.sort(keys, sort); keys.forEach(key -> assertEquals(key, q.removeAux())); } unit test @Test public void testAccuracy() { testAccuracy(new LazyPriorityQueue<>() , Comparator.reverseOrder()); testAccuracy(new EagerPriorityQueue<>(), Comparator.reverseOrder()); testAccuracy(new BinaryHeap<>() , Comparator.reverseOrder()); testAccuracy(new LazyPriorityQueue<Integer> (Comparator.reverseOrder()), Comparator.naturalOrder()); testAccuracy(new EagerPriorityQueue<Integer>(Comparator.reverseOrder()), Comparator.naturalOrder()); testAccuracy(new BinaryHeap<Integer> (Comparator.reverseOrder()), Comparator.naturalOrder()); }
  • 106. Emory University Logo Guidelines - Unit Test - Speed 16
  • 107. Emory University Logo Guidelines - Unit Test - Speed • If you want to see if your program runs as fast as it should, 16
  • 108. Emory University Logo Guidelines - Unit Test - Speed • If you want to see if your program runs as fast as it should, - The best way is using a profiler (e.g., JProfiler). 16
  • 109. Emory University Logo Guidelines - Unit Test - Speed • If you want to see if your program runs as fast as it should, - The best way is using a profiler (e.g., JProfiler). - The easiest way is measuring the time between operations. 16
  • 110. Emory University Logo Guidelines - Unit Test - Speed • If you want to see if your program runs as fast as it should, - The best way is using a profiler (e.g., JProfiler). - The easiest way is measuring the time between operations. 16 <T extends Comparable<T>>long getRuntime(int warm, int iter, AbstractPriorityQueue<T> q) { long st, et; for (int i=0; i<warm; i++) q.remove(); st = System.currentTimeMillis(); for (int i=0; i<iter; i++) q.remove(); et = System.currentTimeMillis(); return et - st; }
  • 111. Emory University Logo Guidelines - Unit Test - Speed • If you want to see if your program runs as fast as it should, - The best way is using a profiler (e.g., JProfiler). - The easiest way is measuring the time between operations. 16 <T extends Comparable<T>>long getRuntime(int warm, int iter, AbstractPriorityQueue<T> q) { long st, et; for (int i=0; i<warm; i++) q.remove(); st = System.currentTimeMillis(); for (int i=0; i<iter; i++) q.remove(); et = System.currentTimeMillis(); return et - st; } warm-up
  • 112. Emory University Logo Guidelines - Unit Test - Speed • If you want to see if your program runs as fast as it should, - The best way is using a profiler (e.g., JProfiler). - The easiest way is measuring the time between operations. 16 <T extends Comparable<T>>long getRuntime(int warm, int iter, AbstractPriorityQueue<T> q) { long st, et; for (int i=0; i<warm; i++) q.remove(); st = System.currentTimeMillis(); for (int i=0; i<iter; i++) q.remove(); et = System.currentTimeMillis(); return et - st; } warm-up operation
  • 113. Emory University Logo Guidelines - Speed Comparison - Add 17 Milliseconds 0 150 300 450 600 Queue sizes 100 200 300 400 500 600 700 800 900 1000 Lazy Eager Heap
  • 114. Emory University Logo Guidelines - Speed Comparison - Add 17 Milliseconds 0 150 300 450 600 Queue sizes 100 200 300 400 500 600 700 800 900 1000 Lazy Eager Heap O(1)
  • 115. Emory University Logo Guidelines - Speed Comparison - Add 17 Milliseconds 0 150 300 450 600 Queue sizes 100 200 300 400 500 600 700 800 900 1000 Lazy Eager Heap Both O(log n)?O(1)
  • 116. Emory University Logo Guidelines - Speed Comparison - Remove 18 Milliseconds 0 1000 2000 3000 4000 Queue sizes 100 200 300 400 500 600 700 800 900 1000 Lazy Eager Heap
  • 117. Emory University Logo Guidelines - Speed Comparison - Remove 18 Milliseconds 0 1000 2000 3000 4000 Queue sizes 100 200 300 400 500 600 700 800 900 1000 Lazy Eager Heap O(1)
  • 118. Emory University Logo Guidelines - Speed Comparison - Remove 18 Milliseconds 0 1000 2000 3000 4000 Queue sizes 100 200 300 400 500 600 700 800 900 1000 Lazy Eager Heap O(1) O(log n)
  • 119. Emory University Logo Guidelines - Speed Comparison - Remove 18 Milliseconds 0 1000 2000 3000 4000 Queue sizes 100 200 300 400 500 600 700 800 900 1000 Lazy Eager Heap O(n) O(1) O(log n)
  • 120. Emory University Logo Guidelines - Agenda • Exercise - https://github.com/emory-courses/cs323/wiki/Priority-Queues • Reading - https://en.wikipedia.org/wiki/Selection_sort - https://en.wikipedia.org/wiki/Insertion_sort - https://en.wikipedia.org/wiki/Heapsort - https://en.wikipedia.org/wiki/Shellsort 19