Insert 35, 33, 42, 10, 14, 19, 27, 44, 26, 31 one at a time into an initially empty max-heap. Give the final array.
A priority queue always serves the element with the highest (or lowest) priority first. The binary heap — a complete binary tree stored in an array — gives O(log n) insert and delete-max/min, O(n) build, and powers heap sort, Dijkstra, Prim and schedulers.
A priority queue is a collection in which every element carries a priority, and removal always takes the element with the highest priority rather than the oldest one. In a max-priority queue (descending priority queue) the largest key leaves first; in a min-priority queue (ascending priority queue) the smallest key does. Elements with equal priority may leave in any order unless the implementation deliberately breaks ties by arrival time.
| Operation | Meaning |
|---|---|
| insert(x) | add x with its priority |
| findMax() / peek() | return the highest-priority element without removing it |
| deleteMax() / extractMax() | remove and return the highest-priority element |
| increaseKey(x, k) | raise x's priority to k (a min-PQ has decreaseKey instead) |
| isEmpty(), size() | status queries |
A* search does the same with estimated costs.A priority queue can be built on almost any structure; the question is which operation you are willing to make slow. Unsorted structures make insertion cheap and deletion expensive; sorted structures do the opposite. The heap balances the two.
| Implementation | insert | findMax | deleteMax | Remarks |
|---|---|---|---|---|
| Unsorted array or linked list | O(1) | O(n) | O(n) | append anywhere; scan to find the maximum |
| Sorted array (ascending, max at the end) | O(n) | O(1) | O(1) | binary search finds the slot in O(log n), but shifting costs O(n) |
| Sorted linked list (descending) | O(n) | O(1) | O(1) | walk to the insertion point; delete the head |
| Binary heap | O(log n) | O(1) | O(log n) | complete tree in an array — the standard choice |
| Balanced BST (AVL, red–black) | O(log n) | O(log n) | O(log n) | also supports sorted traversal and deleting any key |
| Array of k FIFO queues (one per level) | O(1) | O(k) | O(k) | good when there are few priority levels, as in OS schedulers |
| Fibonacci heap | O(1) amortised | O(1) | O(log n) amortised | decrease-key O(1) amortised → Dijkstra in O(E + V log V) |
A binary heap satisfies two properties. Shape: it is a complete binary tree — every level is full except possibly the last, which is filled from the left with no gaps. Order: in a max-heap every node's key is ≥ the keys of its children, so the root holds the maximum; in a min-heap every node is ≤ its children and the root holds the minimum. Nothing is said about left versus right children, so a heap is not a binary search tree.
Because the tree is complete, it can be stored level by level in an ordinary array with no pointers at all: the root in the first cell, then its two children, then the four grandchildren, and so on. Parent and child positions are computed by arithmetic, and a heap of n nodes has height ⌊log₂ n⌋ — the number of edges on its longest root-to-leaf path.
40 [0]
/ \
30 [1] 15 [2]
/ \
10 [3] 20 [4]| Quantity | 0-based array (C, Java) | 1-based array (many textbooks) |
|---|---|---|
| Root | index 0 | index 1 |
| Parent of i | ⌊(i − 1)/2⌋ | ⌊i/2⌋ |
| Left child of i | 2i + 1 | 2i |
| Right child of i | 2i + 2 | 2i + 1 |
| Last internal (non-leaf) node | ⌊n/2⌋ − 1 | ⌊n/2⌋ |
| Leaves | ⌊n/2⌋ … n − 1 | ⌊n/2⌋ + 1 … n |
a[i] >= a[2i+1] and a[i] >= a[2i+2] for every internal node i (0-based). Example: [50, 30, 40, 20, 25, 35, 10, 5] passes; [50, 30, 40, 20, 35, 25, 45, 5] fails because 35 > 30 and 45 > 40.| Insert | Placed at | Sift-up swaps | Array afterwards |
|---|---|---|---|
| 10 | index 0 | none (root) | 10 |
| 20 | index 1 | 20 > parent 10 → swap | 20, 10 |
| 15 | index 2 | 15 < parent 20 → none | 20, 10, 15 |
| 30 | index 3 | 30 > 10 → swap; 30 > 20 → swap | 30, 20, 15, 10 |
| 40 | index 4 | 40 > 20 → swap; 40 > 30 → swap | 40, 30, 15, 10, 20 |
The new key always travels up a single root-to-leaf path, which is why only O(log n) work is needed even though the array may hold millions of keys. increaseKey in a max-heap is the same sift-up started from the changed node.
#include <stdio.h>
#define CAP 100
int heap[CAP];
int n = 0; /* number of elements */
void swap(int *a, int *b) { int t = *a; *a = *b; *b = t; }
void siftUp(int i) { /* O(log n) */
while (i > 0 && heap[(i - 1) / 2] < heap[i]) {
swap(&heap[(i - 1) / 2], &heap[i]);
i = (i - 1) / 2; /* continue from the parent */
}
}
void siftDown(int i) { /* O(log n) */
for (;;) {
int l = 2 * i + 1, r = 2 * i + 2, big = i;
if (l < n && heap[l] > heap[big]) big = l;
if (r < n && heap[r] > heap[big]) big = r;
if (big == i) break; /* heap order restored */
swap(&heap[i], &heap[big]);
i = big;
}
}
void insert(int key) {
if (n == CAP) { printf("heap full\n"); return; }
heap[n] = key; /* next free leaf keeps the tree complete */
siftUp(n++);
}
int deleteMax(void) { /* caller must ensure n > 0 */
int max = heap[0];
heap[0] = heap[--n]; /* last leaf moves to the root */
siftDown(0);
return max;
}
void buildHeap(const int a[], int len) { /* Floyd's bottom-up method: O(n) */
for (n = 0; n < len; n++) heap[n] = a[n];
for (int i = n / 2 - 1; i >= 0; i--) siftDown(i);
}
void show(void) { for (int i = 0; i < n; i++) printf("%d ", heap[i]); printf("\n"); }
int main(void) {
int keys[] = {10, 20, 15, 30, 40};
for (int i = 0; i < 5; i++) insert(keys[i]);
show(); /* 40 30 15 10 20 */
printf("deleteMax = %d -> ", deleteMax());
show(); /* 30 20 15 10 */
int a[] = {4, 1, 3, 2, 16, 9, 10, 14, 8, 7};
buildHeap(a, 10);
show(); /* 16 14 10 8 7 9 3 2 4 1 */
return 0;
}In the run above, deleteMax removes 40 and moves the last key 20 to the root: [20, 30, 15, 10]. The larger child of 20 is 30, so they swap, giving [30, 20, 15, 10]; 20's only child is now 10, so sifting stops. Related operations reuse the same two routines: decreaseKey in a max-heap sifts down, and deleting the element at an arbitrary index i replaces it with the last element and then sifts up or down as needed.
Inserting n keys one by one costs O(n log n). Robert Floyd's bottom-up build-heap (1964) is faster: copy the keys into the array as they are, then call siftDown on every internal node from the last one, ⌊n/2⌋ − 1, back to the root. Leaves are already one-element heaps, and by the time a node is processed both of its subtrees are heaps, so one sift-down fixes it.
| siftDown at | Key | What happens | Array afterwards |
|---|---|---|---|
| i = 4 | 16 | only child 7 is smaller — no change | 4, 1, 3, 2, 16, 9, 10, 14, 8, 7 |
| i = 3 | 2 | larger child 14 → swap | 4, 1, 3, 14, 16, 9, 10, 2, 8, 7 |
| i = 2 | 3 | larger child 10 → swap | 4, 1, 10, 14, 16, 9, 3, 2, 8, 7 |
| i = 1 | 1 | swap with 16, then with 7 | 4, 16, 10, 14, 7, 9, 3, 2, 8, 1 |
| i = 0 | 4 | swap with 16, then 14, then 8 | 16, 14, 10, 8, 7, 9, 3, 2, 4, 1 |
Inserting the same ten keys one at a time gives a different, equally valid heap: [16, 14, 10, 8, 7, 3, 9, 1, 4, 2]. A set of keys usually has many valid heaps, so an MCQ answer must follow the method the question specifies.
Heap sort (J. W. J. Williams, 1964) builds a max-heap and then repeatedly swaps the root with the last element of the heap, shrinks the heap by one and sifts the new root down. The array ends up in ascending order after n − 1 such steps: O(n log n) in the best, average and worst cases, O(1) extra space, but not stable (equal keys can change their relative order). The Sorting topic traces it in full.
std::priority_queue is a max-heap by defaultPriorityQueue and Python heapq are min-heapsVariants: a d-ary heap gives each node d children (children of i at d·i + 1 … d·i + d, 0-based), making the tree shallower — useful for Dijkstra on dense graphs. Binomial heaps support merging two heaps in O(log n), and Fibonacci heaps (Fredman and Tarjan, 1984) make insert and decrease-key O(1) amortised.
Try the problem first, then reveal the working one step at a time.
Insert 35, 33, 42, 10, 14, 19, 27, 44, 26, 31 one at a time into an initially empty max-heap. Give the final array.
Perform deleteMax twice on the heap [44, 42, 35, 33, 31, 19, 27, 10, 26, 14].
Build a max-heap from [5, 3, 8, 1, 9, 2] (a) bottom-up and (b) by inserting the keys left to right. Compare the results.
A heap is stored in an array. Give the parent and children of the node at index 13 if the array is (a) 1-based, (b) 0-based. In a 0-based heap of 20 elements, which indices hold leaves?
Insert 50 into the max-heap [45, 30, 40, 10, 20, 35]. Show each swap and the final array.
Perform deleteMin on the min-heap [2, 5, 3, 9, 6, 4, 8].
Is [90, 70, 80, 60, 75, 50, 85] a max-heap? If not, convert it into one with the bottom-up method.
A max-heap holds 31 elements. What is the maximum number of swaps when one more element is inserted? Why?
10 questions. 70 % passes the topic quiz (+30 XP, +20 more for 100 %). Exam scoring: +1 correct, −⅓ wrong.
Modelled on real KPSC questions (reworded) with the same concept and answer; each links to its original paper.