PriorityQueue.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. import ArrayList from '../../../../java/util/ArrayList'
  2. export default class PriorityQueue {
  3. constructor() {
  4. PriorityQueue.constructor_.apply(this, arguments)
  5. }
  6. poll() {
  7. if (this.isEmpty()) return null
  8. const minItem = this._items.get(1)
  9. this._items.set(1, this._items.get(this._size))
  10. this._size -= 1
  11. this.reorder(1)
  12. return minItem
  13. }
  14. size() {
  15. return this._size
  16. }
  17. reorder(hole) {
  18. let child = null
  19. const tmp = this._items.get(hole)
  20. for (; hole * 2 <= this._size; hole = child) {
  21. child = hole * 2
  22. if (child !== this._size && this._items.get(child + 1).compareTo(this._items.get(child)) < 0)
  23. child++
  24. if (this._items.get(child).compareTo(tmp) < 0)
  25. this._items.set(hole, this._items.get(child))
  26. else
  27. break
  28. }
  29. this._items.set(hole, tmp)
  30. }
  31. clear() {
  32. this._size = 0
  33. this._items.clear()
  34. }
  35. peek() {
  36. if (this.isEmpty()) return null
  37. const minItem = this._items.get(1)
  38. return minItem
  39. }
  40. remove(o) {
  41. return this._items.remove(o)
  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. getClass() {
  56. return PriorityQueue
  57. }
  58. get interfaces_() {
  59. return []
  60. }
  61. }
  62. PriorityQueue.constructor_ = function() {
  63. this._size = null
  64. this._items = null
  65. this._size = 0
  66. this._items = new ArrayList()
  67. this._items.add(null)
  68. }