algoritmauzmanı
Sign in
TREN
5.5Priority Queue
Lesson 5.5.2

With an array: inserting by priority

The simplest way to build a with an is to keep the array sorted at all times. In this lesson the array is sorted from large to small: the highest-priority element, the smallest value, sits at the end of the array. When a new element arrives, a slot is opened at the right place for its priority and the value is written there.

What you will learn
  • Why the array is kept sorted from large to small and why the highest-priority element sits at the end
  • How the new element's slot is opened while searching from the end towards the front, and how equal priorities keep their order
  • Why insertion takes and what happens when the queue is full
6 minTime O(n)Memory O(1)C · Java · Python

1Idea

The structure has two fields: the items array and size, which holds the number of elements. The first size cells of the array are in use and the values are sorted from large to small. A smaller value has higher priority, so the highest-priority element is in items[size - 1]. Why at the end? Removal always takes the highest-priority element, and taking an element from the end shifts nothing (removing with an array).

Insertion first checks whether the queue is full. If size == CAPACITY there is no room: in C the function returns false, Java throws IllegalStateException and Python raises IndexError. The message is "queue is full".

If there is room, the search starts at the end: i = size - 1. If items[i] is smaller than or equal to the new value, that element must leave before the new one. So it moves one cell to the right and i goes down by one. The loop stops at a larger value or at the front of the array. The new value is written into the freed cell items[i + 1] and size goes up by one.

This is the same shifting as in the inserting at a position lesson. The only difference is that the position is not given from outside: the shifting stops by itself when it reaches the right place.

The <= in the condition keeps equal priorities in order. The older element with the same value also moves right and stays to the right of the new one, closer to the exit. So the one that arrived first leaves first. With < the new element would jump ahead of its equals.

2Step by step

The drawing inserts 5 into a queue holding 9, 7, 4 and 2. The capacity is 5 and size is 4. The highest-priority element, 2, is at the end of the array. A faded cell has had its value copied to the right and will be overwritten.

0123497425244size5size5valuei
  1. Start. size is 4 and the capacity is 5: there is room. The value to insert is 5.
  2. i = 3: items[3] is 2. 2 is smaller than 5, so it has higher priority. It moves one cell right and i becomes 2.
  3. i = 2: items[2] is 4. 4 is also smaller than 5. It moves one cell right too and i becomes 1.
  4. i = 1: items[1] is 7. 7 is larger than 5, so it has lower priority. The loop stops here and 7 stays where it is.
  5. 5 is written into the freed cell items[i + 1], cell 2.
  6. size becomes 5. The array is still sorted from large to small: 9, 7, 5, 4, 2. The next element to leave is still 2.

#define CAPACITY 5 struct PQ {    int items[CAPACITY];  // sorted from large to small    int size;}; bool insert(struct PQ* pq, int value) {    if (pq->size == CAPACITY) return false;  // the queue is full    int i = pq->size - 1;    while (i >= 0 && pq->items[i] <= value) {  // higher priorities move right        pq->items[i + 1] = pq->items[i];        i--;    }    pq->items[i + 1] = value;    pq->size++;    return true;}
class ArrayPriorityQueue {    int[] items;    int size = 0;   // sorted from large to small     ArrayPriorityQueue(int capacity) {        items = new int[capacity];    }     void insert(int value) {        if (size == items.length) throw new IllegalStateException("queue is full");        int i = size - 1;        while (i >= 0 && items[i] <= value) {  // higher priorities move right            items[i + 1] = items[i];            i--;        }        items[i + 1] = value;        size++;    }}
class ArrayPriorityQueue:    def __init__(self, capacity):        self.items = [None] * capacity  # sorted from large to small        self.size = 0     def insert(self, value):        if self.size == len(self.items):            raise IndexError("queue is full")        i = self.size - 1        while i >= 0 and self.items[i] <= value:  # higher priorities move right            self.items[i + 1] = self.items[i]            i -= 1        self.items[i + 1] = value        self.size += 1

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

3Complexity

Time
O(n)

The loop runs once for each element smaller than or equal to the new value. In the worst case the new value is the largest: all n elements shift and the new element goes into cell 0.

Memory
O(1)

Only the loop counter i is used; the array changes in place.

If the new element has the highest priority nothing shifts and insertion takes . With a linked list insertion is O(n) too, but it walks instead of shifting (inserting with a linked list).

4Common mistake

A common mistake is to search for the slot from the front and also shift from front to back:

int k = 0;while (k < pq->size && pq->items[k] > value) k++;for (int i = k; i < pq->size; i++)   // front to back    pq->items[i + 1] = pq->items[i];

This loop writes items[k] one cell to the right, and the next round carries the same value one more cell right. In the end every cell after k holds the same value. Shifting is always done from the end towards the front. In the lesson code the search and the shift are one loop, so this order comes for free.

5Try it

The queue holds 8, 6, 3 (large to small). What does the array look like after insert(6)?

Show the answer

The answer is A. Because of the <= condition, 3 and the old 6 move right and the loop stops at 8. The new 6 goes into cell 1. The old 6 stays in cell 2, closer to the exit. With equal priorities the one that arrived first leaves first.

A queue with capacity 5 holds 5 elements. What happens if insert(1) is called?

Show the answer

The answer is B. The first line checks size == CAPACITY. If there is no room, no element moves and the queue does not change. The result is the same even though 1 is the highest-priority value.

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