The insert() method checks whether there are any items; if not, it inserts one at
index 0. Otherwise, it starts at the top of the array and shifts existing items upward
until it finds the place where the new item should go. Then it inserts the item and
increments nItems. Note that if there’s any chance the priority queue is full, you
should check for this possibility with isFull() before using insert().
The front and rear fields aren’t necessary as they were in the Queue class because, as
we noted, front is always at nItems-1 and rear is always at 0.
The remove() method is simplicity itself: It decrements nItems and returns the item
from the top of the array. The peekMin() method is similar, except it doesn’t decre-ment nItems. The isEmpty() and isFull() methods check if nItems is 0 or maxSize,
respectively.
Efficiency of Priority Queues
In the priority-queue implementation we show here, insertion runs in O(N) time,
while deletion takes O(1) time.
No comments:
Post a Comment