I have to implement a function with complexity O(log n), that updates priority of an element in the priority queue. That means that given an element, access to its priority should be O(1). I don't really understand how this can be done, if all elements are stored in a heap, and their position is constantly changing, which gives me O(n) search of the element in the heap.
Heap :
public class Heap<K, V> {
private int size;
private Element<K, V> heap[];
private Comparator<? super K> comparator;
public Heap(Comparator<? super K> comparator) {
//
}
//
public void add(K priority, V value) {
int i;
size++;
if(size > heap.size()) resize();
i = size;
heap[i] = new Element(priority, value);
while(i > 0 || comparator.compare(heap[parent(i)].priority, heap[i].priority) < 0) {
swap(i, parent(i));
}
}
// O(log n)
public void updatePriority(int i, K priority) {
K oldPriority = heap[i].priority;
heap[i] = new Element(priority, heap[i].value);
if(comparator.compare(oldPriority, heap[i].priority) > 0) {
heapify(i);
} else {
while(i > 0 && comparator.compare(heap[parent(i)].priority, heap[i].priority)) < 0) {
swap(i, parent(i));
i = parent(i);
}
}
}
}
PriorityQueue:
public class PriorityQueue<K, V> {
private Heap<Element<K, V>> heap;
private Comparator<? super K> comparator;
public PriorityQueue(Comparator<? super K> comparator) {
heap = new Heap<K, V>(comparator);
}
//
// Should be O(log n)
public void updatePriority(K priority, V elem) {
// get index of elem in O(1)
heap.updatePriority(indexOfElem, priority);
}
}
Element:
public class Element<K, V> {
public K priority;
public V value;
public Element(K priority, V value) {
this.priority = priority;
this.value = value;
}
}
This priority queue later should be used to implement Prim's algorithm. So what can I do to get O(1) access complexity?