You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: source/lectures/data/priority_queue.md
+3-44Lines changed: 3 additions & 44 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -123,54 +123,13 @@ The challenge is to restore "the heap property", which is done as follows:
123
123
2. Compare the new root with its children; if they are in the correct order, stop.
124
124
3. If not, swap the element with one of its children and return to the previous step (swaping with the smaller child in a min-heap).
125
125
126
-
The 2nd and 3rd steps are called "percolate-down".
126
+
The 2nd and 3rd steps are called "percolate-down": the idea is that the element that is at the root will "go down" the heap by swapping with elements with smaller priority.
127
+
At each step, we compare its priority with its children priority, and swap it with the children with the lowest priority if it is lower than its own.
128
+
When both children have a higher than or equal priority to its own, we know we are done and can stop.
127
129
128
130
#### Implementing priority queue using heaps implemented as arrays
Heap definitions. The binary heap is a data structure that can efficiently support the basic priority-queue operations. In a binary heap, the items are stored in an array such that each key is guaranteed to be larger than (or equal to) the keys at two other specific positions. In turn, each of those keys must be larger than two more keys, and so forth. This ordering is easy to see if we view the keys as being in a binary tree structure with edges from each key to the two keys known to be smaller.
162
-
163
-
Definition. A binary tree is heap-ordered if the key in each node is larger than (or equal to) the keys in that nodes two children (if any).
164
-
165
-
Proposition. The largest key in a heap-ordered binary tree is found at the root.
166
-
167
-
168
-
We can impose the heap-ordering restriction on any binary tree. It is particularly convenient, however, to use a complete binary tree like the one below.
169
-
170
-
Heap representations
171
-
We represent complete binary trees sequentially within an array by putting the nodes with level order, with the root at position 1, its children at positions 2 and 3, their children in positions 4, 5, 6 and 7, and so on.
172
-
173
-
Definition. A binary heap is a set of nodes with keys arranged in a complete heap-ordered binary tree, represented in level order in an array (not using the first entry).
0 commit comments