felipernb/algorithms.js

PriorityQueue's changePriority method works in linear time

eush77 opened this issue · 3 comments

We can do better, namely in O(log n).

Yeah, it's possible.

But in order to do that without changing the interface we need to add another structure to keep track of the relation: item -> position in the heap and the code can get a little convoluted, but I'll put some thought into it.

I think this can be achieved by overloading _swap to capture swaps (in order to update positions to pass to _siftUp, _siftDown) and changing heap comparator so that it looks up priorities in the PriorityQueue._items rather than in a separate container.

function PriorityQueue(initialItems) {
  MinHeap.call(this, function (a, b) {
    return self._items[a].priority < self._items[b].priority ? -1 : 1;
  });
  /* ... */
}

@felipernb @eush77 I've made a pull reuest with proposed implementation, can you have a look and check it out. Link : #129