Advertisement
wavec022

priority queue notes

Mar 20th, 2020
361
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.93 KB | None | 0 0
  1. Priority Queue
  2.  
  3. Implementing a priority queue using a Scala ArrayBuffer
  4.  
  5. Like a normal queue except each element has a "priority" attached to it
  6.  
  7. There are several ways-- we will look at Array and Heap Ordered Tree (HOT)
  8.  
  9. =====
  10.  
  11. Two invariants-- shape invariant and max or min-heap invariant (these are for a binary tree NOT a binary search tree)
  12. Shape invariant-- insists that all levels are full except for bottom level
  13. Max-heap-- insists that the parent is at least as big as the children (min = at least as small)
  14.  
  15. just make sure max or min heap holds all the way down-- parent node is greater than both of its child nodes
  16.  
  17. How to queue-- put it in the last spot and then "sift" all the way up to restore the invariant
  18.  
  19. How to dequeue-- removing the root node breaks the tree, so swap it with the last element in the queue and then sift DOWN to restore the invariant.
  20. When sifting down, swap with the higher priority element of the two children
  21.  
  22. =====
  23.  
  24. How do we implement this? How do we get the mutable ArrayBuffer to act like the tree?
  25. The ArrayBuffer must hold all the elements and the highest priority element must be the first element in the queue
  26. They can come in random order but they must be placed in the right spot once they show up
  27.  
  28. Once all elements are queued we will dequeue and insert a new one
  29.  
  30. We can calculate where parents/children are using the indices
  31.  
  32. i left = 2i+1
  33. i right = 2i+2
  34. i parent = floor(i-1)/2
  35. ( we don't need floor because of int math so it can just be (i-1)/2 )
  36.  
  37. ===============================
  38.  
  39. HW 9:
  40. https://gyazo.com/ab3e5f18bb10a49e48a9061752896199
  41. and then use x.toString
  42.  
  43. ===============================
  44.  
  45. Queue with Heap is a minheap
  46.  
  47. When we dequeue a heap tree we split the two trees so we need a way to merge them
  48.  
  49. HW 10:
  50. https://gyazo.com/54f40d25696eab899a2867bb3627b797 (case class H)
  51. https://gyazo.com/3c8634a5d965ca75824502f72156c65f (size and merge and stuff)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement