Binary heaps: sift up and sift down
لم يُترجم بعد؛ يُعرض باللغة الإنجليزية
عن هذا الدرس
A heap keeps the smallest item on top without sorting everything. Here it is a plain Python list read as a tree: index 0 is the root and the children of i sit at 2i + 1 and 2i + 2. Watch heappush(h, 1) append and sift up three levels, then heappop(h) move the last item to the root and sift it down, one swap per level. The Software lessons "Trees" and "How fast is fast? Big O" cover binary trees and O(log n).
A list read as a tree
A binary heap is a plain Python list read as a tree. h[0] is the root. The item at index i has its children at 2i + 1 and 2i + 2, and its parent at (i − 1) // 2. No pointers are stored.
h = [2, 4, 3, 8, 5, 7, 6] parent = (i - 1) // 2 left = 2 * i + 1 right = 2 * i + 2 i = 0: children 1, 2 (values 4, 3) i = 1: children 3, 4 (values 8, 5) i = 2: children 5, 6 (values 7, 6) i = 6: parent (6 - 1) // 2 = 2
اقرأ الدرس خطوة بخطوة
A list read as a tree
A binary heap is a plain Python list read as a tree. h[0] is the root. The item at index i has its children at 2i + 1 and 2i + 2, and its parent at (i − 1) // 2. No pointers are stored.
h = [2, 4, 3, 8, 5, 7, 6] parent = (i - 1) // 2 left = 2 * i + 1 right = 2 * i + 2 i = 0: children 1, 2 (values 4, 3) i = 1: children 3, 4 (values 8, 5) i = 2: children 5, 6 (values 7, 6) i = 6: parent (6 - 1) // 2 = 2The heap rule
The rule: every parent is less than or equal to its children. So the smallest item is always h[0]. The rest is only loosely ordered: [2, 4, 3, 8, 5, 7, 6] is a valid heap, but it is not sorted.
min-heap rule: h[i] <= h[2*i + 1] and h[i] <= h[2*i + 2] h[0] = 2 <= h[1] = 4 h[0] = 2 <= h[2] = 3 h[1] = 4 <= h[3] = 8 h[1] = 4 <= h[4] = 5 h[2] = 3 <= h[5] = 7 h[2] = 3 <= h[6] = 6 so h[0] = 2 is the smallest, yet 8 comes before 5, 7 and 6: not sortedPush: append at the end
heapq.heappush(h, 1) first appends 1 at the end, index 7. The tree stays complete: filled level by level, left to right. Its parent is at (7 − 1) // 2 = 3 and holds 8. 8 > 1 breaks the rule.
def push(h, x): h.append(x) sift_up(h, len(h) - 1) h.append(1) -> index 7 h = [2, 4, 3, 8, 5, 7, 6, 1] parent of 7 = (7 - 1) // 2 = 3, h[3] = 8 > 1Sift up
Sift up: while the new item is smaller than its parent, swap the two. 1 swaps with 8, then with 4, then with 2. Now it is the root, so it stops: 3 swaps, one per level.
def sift_up(h, i): while i > 0: p = (i - 1) // 2 if h[p] <= h[i]: break h[p], h[i] = h[i], h[p] i = p swap h[3] and h[7] swap h[1] and h[3] swap h[0] and h[1] h = [1, 2, 3, 4, 5, 7, 6, 8]Pop: take the root
heapq.heappop(h) returns h[0], the smallest item: 1. To keep the tree complete, the last item, 8 from index 7, moves into the root. The list is back to 7 items, but 8 on top breaks the rule.
def pop(h): top = h[0] last = h.pop() if h: h[0] = last sift_down(h, 0) return top top = h[0] = 1 last item 8 moves from index 7 to index 0 h = [8, 2, 3, 4, 5, 7, 6] children of 0: h[1] = 2, h[2] = 3, both < 8Sift down
Sift down: swap the item with its smaller child while that child is smaller. The smaller one, so the new parent is no bigger than the other child. 8 swaps with 2, then with 4. Index 3 has no children left, so it stops.
def sift_down(h, i): n = len(h) while 2 * i + 1 < n: c = 2 * i + 1 if c + 1 < n and h[c + 1] < h[c]: c += 1 if h[i] <= h[c]: break h[i], h[c] = h[c], h[i] i = c i = 0: children 2, 3 -> smaller is 2 (index 1) < 8: swap i = 1: children 4, 5 -> smaller is 4 (index 3) < 8: swap i = 3: left child 7 is not < len(h) = 7: stop h = [2, 4, 3, 8, 5, 7, 6]One swap per level
Each swap moves one level. A complete tree of n items has ⌊log₂ n⌋ + 1 levels, so a sift makes at most ⌊log₂ n⌋ swaps: 3 for 8 items, 19 for a million. Push and pop are O(log n); reading h[0] is O(1).
levels of a complete tree with n items: floor(log2 n) + 1 n = 7 levels 3 max swaps 2 n = 8 levels 4 max swaps 3 n = 15 levels 4 max swaps 3 n = 16 levels 5 max swaps 4 n = 1000 levels 10 max swaps 9 n = 1000000 levels 20 max swaps 19 push: O(1) amortised append + O(log n) sift up pop: O(1) list pop + O(log n) sift down peek: h[0], O(1)Python's heapq
Python's heapq module does exactly this to a plain list. heappush(h, 1) then heappop(h) returns 1 and leaves h = [2, 4, 3, 8, 5, 7, 6] again. It is a min-heap; Python 3.14 adds heappush_max and heappop_max for a max-heap.
import heapq h = [2, 4, 3, 8, 5, 7, 6] heapq.heappush(h, 1) h # [1, 2, 3, 4, 5, 7, 6, 8] heapq.heappop(h) # 1 h # [2, 4, 3, 8, 5, 7, 6] h[0] # 2, the smallest, without popping
أسئلة سريعة: 5
اختر إجابة واحدة لكل سؤال. يمكنك تغيير اختياراتك قبل التحقق منها.
01In a list-based heap, which index is the parent of index 9?
parent = (i − 1) // 2 = 8 // 2 = 4. Check: the children of 4 are 2·4 + 1 = 9 and 2·4 + 2 = 10.
02Which of these lists is a valid min-heap?
Every parent must be ≤ its children. In [1, 3, 2, 6, 4, 5]: 1 ≤ 3, 2; 3 ≤ 6, 4; 2 ≤ 5. The others break it: 3 > 0, 2 > 1, and 5 > 4.
03You push 0 onto h = [2, 4, 3, 8, 5, 7, 6]. How many swaps does sift up make?
0 is appended at index 7 and is smaller than every parent on its way: it swaps with 8 (index 3), 4 (index 1) and 2 (index 0). Three swaps, one per level, then it is the root.
04During sift down, why swap with the smaller of the two children?
The child that moves up becomes the parent of the other child. Only the smaller one is ≤ its sibling, so swapping with the larger would break the rule at once.
05A heap holds 1,000,000 items. At most how many swaps can one heappush make?
A complete tree of n items has ⌊log₂ n⌋ + 1 levels: 20 for a million. The new item can climb at most from the bottom level to the top, so at most 19 swaps.
المسرد
- Binary heap
- A complete binary tree, usually stored in a plain list, where every parent obeys an order rule with its children.
- Min-heap
- A heap where every parent is ≤ its children, so the smallest item is at the root, h[0]. Python's heapq is a min-heap.
- Complete tree
- A binary tree filled level by level, left to right, with no gaps. That is what lets it live in a list with no pointers.
- Sift up
- After a push: swap the new item with its parent while it is smaller, until it reaches the root or a smaller parent.
- Sift down
- After a pop: swap the item at the root with its smaller child while that child is smaller, until it reaches a leaf or fits.
- Priority queue
- A collection where you can add items and always take out the most important one first. A heap is the usual way to build one.
- Peek
- Read the top item without removing it. In a heap that is h[0], O(1).
الملاحظات والمصادر
- Python and MIT 6.006 count from index 0, so the children of i are 2i + 1 and 2i + 2. CLRS and Sedgewick and Wayne count from 1 and use 2i and 2i + 1, with the parent at i // 2. Same tree, shifted by one.
- This is a min-heap: the smallest item is on top. Many textbooks show a max-heap (largest on top, sift down swaps with the larger child). The steps are the same with every comparison flipped.
- heapq's heappop uses a faster variant of sift down: it moves the smaller child up all the way to a leaf, then sifts the item back up a little, which saves comparisons. On this example it gives exactly the same list.
- A complete tree has 2^d slots at depth d, so n items need ⌊log₂ n⌋ + 1 levels (CLRS chapter 6: an n-element heap has height ⌊lg n⌋). Sift up and sift down each move at most that height.
- The code in the step details is real Python 3. push and pop run on a plain list, and the tests check them against heapq on thousands of random lists.
- Python documentation: heapq, heap queue algorithm
- CPython source: Lib/heapq.py
- MIT 6.006 Introduction to Algorithms (Spring 2020), Lecture 8: Binary Heaps
- Sedgewick and Wayne, Algorithms 4th ed., §2.4 Priority Queues
- Cormen, Leiserson, Rivest and Stein, Introduction to Algorithms, 4th ed. (MIT Press, 2022), chapter 6
- Python tutorial: More on lists (append and pop)
اختبار يتاح بعد الخطوة الأخيرة.