61B part 5.3 Prior Queues&heap
Priority Queue interface
1 | public interface MinPQ<item>{ |
Task: use the interface to track the M best
core code:
1 | if(unharmoniousTests.size() > M) unharmoniousTests.removeSmallest(); |
perfect implementation–heap
Heap
We will define our binary min-heap as being complete and obeying min-heap property:
- Min-heap: Every node is less than or equal to both of its children
- Complete: Missing items only at the bottom level (if any), all nodes are as far left as possible.
![[Pasted image 20240427225515.png]]
The green ones are correct min-heaps and red ones are not.
we can see that as the root is smaller than all its children, it is smaller than anyone in the queue.
Implementation
getSmallest: return the root nodeadd:
- add the element to the bottom left position
- exchange it with the upper ones to ensure the characters
removeSmallest: remove the root, and then move the element on the bottom to the top, then exchanging
Tree implementation in Java
1. create map from parent to children
1.1.
![[Pasted image 20240428142605.png]]
1 | public class Tree1A<Key>{ |
1.2.
![[Pasted image 20240428142731.png]]
1 | public class Tree1B<Key>{ |
1.3.
![[Pasted image 20240428142927.png]]
1 | public class Tree1C<Key>{ |
store keys in an array(similar to that in union-find sets)
![[Pasted image 20240428143407.png]]
store keys in an array. Do not store structures
only works for complete trees
1 | public void swim(int k) |
3.2(book implementation):
Store keys in an array. Offset everything by 1 spot.
- leave spot 0 empty.
- make computation of parents and kids easier.
complexity for each Implementation of PQs:
![[Pasted image 20240428151149.png]]
memory complexity, code simplexity considered, heap is the easiest one.
Summary: search data structures
![[Pasted image 20240428152036.png]]
All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.
