algorithms.js icon indicating copy to clipboard operation
algorithms.js copied to clipboard

PriorityQueue's changePriority method works in linear time

Open eush77 opened this issue 11 years ago • 3 comments

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

eush77 avatar Aug 02 '14 14:08 eush77

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.

felipernb avatar Aug 03 '14 15:08 felipernb

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;
  });
  /* ... */
}

eush77 avatar Aug 03 '14 16:08 eush77

@felipernb @eush77 I've made a pull reuest with proposed implementation, can you have a look and check it out. Link : https://github.com/felipernb/algorithms.js/pull/129

ghost avatar Jul 12 '18 19:07 ghost