algoritmauzmanı
Sign in
TREN
5.5Priority Queue
Lesson 5.5.3

With an array: removing the highest priority

Removal from a always takes the highest-priority element. During insertion the array is kept sorted from large to small, so this element, the smallest value, is always at the end. To remove it you read it and decrease size by one; no element shifts.

What you will learn
  • How removal from an empty queue is prevented
  • Why the highest-priority element is items[size - 1] and why removal only decreases size
  • How removeMin and are written in C, Java and Python, and why they take
5 minTime O(1)Memory O(1)C · Java · Python

1Idea

First the queue is checked for being empty: isEmpty returns true when size == 0. Removing an element from an empty queue is an . In C removeMin returns false; Java throws IllegalStateException and Python raises IndexError. The message is "queue is empty".

If the queue is not empty, the highest-priority element is in items[size - 1]. The value is read and size goes down by one. The old value in the cell is not erased. Since size is smaller, the cell now counts as outside the queue and the next insertion writes over it. This is the same as deleting from the end of an array.

looks without removing: it makes the same check and reads the same cell, but leaves size alone.

If the array were sorted from small to large, the highest-priority element would be in cell 0. Removing it would mean shifting every element behind it one cell left, and removal would take . That is why the array is sorted from large to small.

2Step by step

The drawing removes from a full queue holding 9, 7, 5, 4 and 2. The highest-priority element, 2, is at the end.

01234975425size4size2value
  1. Start. size is 5. The element to leave is the smallest value, 2. It sits in the last used cell of the array, cell 4.
  2. isEmpty returns false, because size is not 0. Removal can go ahead.
  3. items[size - 1], that is items[4], is read: value becomes 2.
  4. size becomes 4. 2 is still in memory but now outside the queue; the next insertion may write over it.
  5. Result: 9, 7, 5, 4 remain in the queue. The next highest-priority element is 4, again at the end. The function hands back 2; in C it returns true.

#define CAPACITY 5 struct PQ {    int items[CAPACITY];  // sorted from large to small    int size;}; bool isEmpty(struct PQ* pq) {    return pq->size == 0;} bool removeMin(struct PQ* pq, int* value) {    if (isEmpty(pq)) return false;  // the queue is empty    *value = pq->items[pq->size - 1];  // the smallest value is at the end    pq->size--;    return true;} bool peek(struct PQ* pq, int* value) {    if (isEmpty(pq)) return false;    *value = pq->items[pq->size - 1];    return true;}
class ArrayPriorityQueue {    int[] items;    int size = 0;   // sorted from large to small     ArrayPriorityQueue(int capacity) {        items = new int[capacity];    }     boolean isEmpty() {        return size == 0;    }     int removeMin() {        if (isEmpty()) throw new IllegalStateException("queue is empty");        int value = items[size - 1];  // the smallest value is at the end        size--;        return value;    }     int peek() {        if (isEmpty()) throw new IllegalStateException("queue is empty");        return items[size - 1];    }}
class ArrayPriorityQueue:    def __init__(self, capacity):        self.items = [None] * capacity  # sorted from large to small        self.size = 0     def is_empty(self):        return self.size == 0     def remove_min(self):        if self.is_empty():            raise IndexError("queue is empty")        value = self.items[self.size - 1]  # the smallest value is at the end        self.size -= 1        return value     def peek(self):        if self.is_empty():            raise IndexError("queue is empty")        return self.items[self.size - 1]

The snippets focus on the operation in this lesson. The C examples need stdlib.h.

3Complexity

Time
O(1)

Independent of the number of elements: one comparison, one read, one decrement.

Memory
O(1)

No extra memory is used.

The price of this speed is paid at insertion: keeping the array sorted makes insertion . With a linked list removal is O(1) as well (removing with a linked list).

4Common mistake

A common mistake is to swap the order of the two lines:

pq->size--;*value = pq->items[pq->size - 1];   // reads the second to last

If size goes down first, size - 1 now points to the second to last element. 4 is read instead of 2, and 2 is silently lost. Either read first and then decrement, or decrement and then read items[size].

5Try it

The queue holds 8, 6, 6, 3 (large to small). What do two calls to removeMin() return?

Show the answer

The answer is A. Removal always takes the smallest value at the end. The first call returns 3, size becomes 3 and a 6 is now at the end. The second call returns that 6, which is the one of the two 6s that was inserted first.

What is the difference between peek() and removeMin()?

Show the answer

The answer is B. Both read items[size - 1] and both report an error on an empty queue. peek does not change the queue; removeMin decreases size by one.

Lessons you mark show up in the curriculum. If you are signed in, they are saved to your account too.