170 likes | 421 Views
Priority Queue. most urgent first, not first in the line. Priority Queue. collection of items each item has a priority associated with it only element that can be removed is element with highest priorityno access to interior of collection. remove element. insert new element. 40. 28. 52.
E N D
Priority Queue most urgent first, not first in the line
Priority Queue • collection of items • each item has a priority associated with it • only element that can be removed is element with highest priorityno access to interior of collection remove element insert new element 40 28 52 93 26 80 D. Goforth, COSC 2006, fall 2003
Priority Queue applications • multi-tasking operating system • Cinefest movie line-up • hospital emergency room D. Goforth, COSC 2006, fall 2003
Queues and Priority Queues • queue • priority queue (conceptual) insert new element remove element 40 78 12 33 26 80 rear front remove element insert new element 90 28 52 93 26 80 D. Goforth, COSC 2006, fall 2003
Priority Queue methods (same) • public void insert (Object item) • add new item to priority queue(enqueue) • public Object getFront() • remove item of highest priority(dequeue) if there are many items of same priority, remove item inserted first • public boolean isEmpty() • true when no items in priority queue • public int size() • number of items in priority queue D. Goforth, COSC 2006, fall 2003
Implementations – many variations • list • array • array of queues D. Goforth, COSC 2006, fall 2003
implementation as array of queues • useful with small number of priorities (i.e., many elements have same priority) • e.g. Cinefest line-ups 1st 2nd 3rd D. Goforth, COSC 2006, fall 2003
Linked listimplementation of a priority queue extend Queue class and override insert method so elements are kept in priority order q.insert(“pppp”); pppp 5 aaa mm tttt xxx q manyNodes 4 front rear D. Goforth, COSC 2006, fall 2003
implementation of insertin linked list insert in priority order BUT after elements of same priority insert new element 43 28 32 43 49 80 D. Goforth, COSC 2006, fall 2003
The insert method public void insert (Object item) { if (isEmpty()) { front = new Node(item, null); // only item in queue rear = front; } else if (((Event)item).compareTo ( front.getData() ) < 0) // before first front = new Node(item,front); else if ( ((Event)item).compareTo ( rear.getData() ) >= 0 ) // after last { rear.addNodeAfter(item); rear = rear.getLink(); } else // in the interior of the list { Node cursor = front; while ( ((Event)item).compareTo ( cursor.getLink().getData() ) >= 0) cursor = cursor.getLink(); cursor.addNodeAfter(item); } manyNodes++; } D. Goforth, COSC 2006, fall 2003