Updating the priority of an element already in the priority queue is an important operation, and the priority queue that does not offer this operation is more or less useless.
The implementation of the priority queue, which allows updating an already inserted value at O ββ(log n) time , is as follows:
import java.util.*; public class PQueue<E extends Comparable<E>> { public static class PQItem<E extends Comparable<E>> implements Comparable<PQItem<E>> { private E m_data; private int m_index; public PQItem(E data, int index) { m_data = data; m_index = index; } public int compareTo(PQItem<E> item) { return m_data.compareTo(item.m_data); } public E getData() { return m_data; } public void setIndex(int index) { m_index = index; } public int getIndex() { return m_index; } } private ArrayList<PQItem<E>> m_array; public PQueue() { m_array = new ArrayList<PQItem<E>>(); } public PQueue(Collection<? extends E> c) { m_array = new ArrayList<PQItem<E>>(c.size());
And here are three small examples of using the priority queue.
static void showMinHeap() { Integer[] values = { 7, 9, 6, 3, 5, 1, 2, 8, 4, 0}; PQueue<Integer> pq = new PQueue<Integer>(Arrays.asList(values)); int lev = 1, i = 0; PQueue.PQItem<Integer> item = pq.getFirstItem(); while(item != null) { if (i == lev) { System.out.println(); lev <<= 1; i = 0; } System.out.print(item.getData()); System.out.print(' '); i++; item = pq.getNextItem(item); } System.out.println(); } static void heapSort() { Integer[] values = { 7, 9, 6, 3, 5, 1, 2, 8, 4, 0}; PQueue<Integer> pq = new PQueue<Integer>(Arrays.asList(values)); for(int i=0; i < values.length; i++) { System.out.print(pq.removeFirst()); System.out.print(' '); } System.out.println(); } static void testNodes() { class Node implements Comparable<Node> { private int m_key; public Node(int k) { m_key = k; } public void updateKey() { m_key *= 2; } public int compareTo(Node v) { return (m_key == v.m_key) ? 0 : (m_key < v.m_key) ? -1 : 1; } public String toString() { return String.valueOf(m_key); } } PQueue<Node> pq= new PQueue<Node>(); Random rand = new Random(7777); final int size = 20; for (int i = 0; i < size; i++) { Node v = new Node(rand.nextInt(size)); pq.add(v); } for (int i = 0; i < size; i++) {
source share