PriorityQueue.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import ArrayList from '../../../../java/util/ArrayList'
  2. export default class PriorityQueue {
  3. constructor() {
  4. PriorityQueue.constructor_.apply(this, arguments)
  5. }
  6. static constructor_() {
  7. this._size = null
  8. this._items = null
  9. this._size = 0
  10. this._items = new ArrayList()
  11. this._items.add(null)
  12. }
  13. poll() {
  14. if (this.isEmpty()) return null
  15. const minItem = this._items.get(1)
  16. this._items.set(1, this._items.get(this._size))
  17. this._size -= 1
  18. this.reorder(1)
  19. return minItem
  20. }
  21. size() {
  22. return this._size
  23. }
  24. reorder(hole) {
  25. let child = null
  26. const tmp = this._items.get(hole)
  27. for (; hole * 2 <= this._size; hole = child) {
  28. child = hole * 2
  29. if (child !== this._size && this._items.get(child + 1).compareTo(this._items.get(child)) < 0) child++
  30. if (this._items.get(child).compareTo(tmp) < 0) this._items.set(hole, this._items.get(child)); else break
  31. }
  32. this._items.set(hole, tmp)
  33. }
  34. clear() {
  35. this._size = 0
  36. this._items.clear()
  37. }
  38. peek() {
  39. if (this.isEmpty()) return null
  40. const minItem = this._items.get(1)
  41. return minItem
  42. }
  43. isEmpty() {
  44. return this._size === 0
  45. }
  46. add(x) {
  47. this._items.add(null)
  48. this._size += 1
  49. let hole = this._size
  50. this._items.set(0, x)
  51. for (; x.compareTo(this._items.get(Math.trunc(hole / 2))) < 0; hole /= 2)
  52. this._items.set(hole, this._items.get(Math.trunc(hole / 2)))
  53. this._items.set(hole, x)
  54. }
  55. }