private void siftDownUp(int index) { index = removeSiftDown(index); // Swap entry with heap's last entry. heapSize--; // Sift up entry that was previously at the heap's end. siftUp(index, data[heapSize], costs[heapSize]); // Reset sentinel here: costs[heapSize] = Double.MAX_VALUE; }
/** * Adds the specified element to this priority queue, with the given priority. * If the element is already present in the queue, it is not added a second * time. * @param value * @param priority * @return <tt>true</tt> if the element was added to the collection. */ @Override public boolean add(E value, double priority) { if (value == null) { throw new NullPointerException("null values are not supported!"); } // if the element is already present in the queue, return false if (indices[this.getIndex(value)] >= 0) { return false; } else { if (heapSize == data.length) throw new RuntimeException("Heap's underlying storage is overflow!"); this.modCount++; siftUp(heapSize, value, priority); heapSize++; return true; } }
/** * Increases the priority (=decrease the given double value) of the element. * If the element ins not part of the queue, it is added. If the new priority * is lower than the existing one, the method returns <tt>false</tt> * * @return <tt>true</tt> if the elements priority was decreased. */ @Override public boolean decreaseKey(E value, double cost) { // If the element is not yet present in the heap, simply add it. int index = indices[this.getIndex(value)]; if (index < 0) { return this.add(value, cost); } /* * If the cost should be increased, we cannot do this. Therefore we * return false. */ double oldCost = costs[index]; if (oldCost < cost) return false; // update costs in array siftUp(index, value, cost); return true; }