The BinaryHeap structure is a max-heap.
This type of binary heap is used for priority queues, since the
maximum value is always at the root. Popping out the max (i.e.: the
root element), re-arrange the heap so a new maximum is set at the
root.
See ProgramΒ 1 for an illustration.
The property of a max-heap is that each parent must be greater than
its direct children. When inserting a value, it is placed in the first
available place and then moved up until to satisfy the property.
The time complexity of a max-heap is roughly as following:
Getting the max value is πͺ(1).
Popping out the max value is πͺ().
Inserting a new value is πͺ().
Building a new heap from a list of unordered values is πͺ().
ββββ
β98β
ββββ
β± β²
β± β²
ββββ ββββ
β41β β76β
ββββ ββββ
β± β² β± β²
ββββ ββββ ββββ ββββ
β23β β11β β33β β56β
ββββ ββββ ββββ ββββ
β± β² β± β²
ββββ ββββ ββββ ββββ
β 5β β10β β25β β17β
ββββ ββββ ββββ ββββProgramΒ 1:An example of a max heap
The main methods of the BinaryHeap are presented in
TableΒ 1.
TableΒ 1:Some methods of BinaryHeap
Method | Description |
|---|---|
| Moves the elements of another heap into this heap. |
| Removes all elements. |
| Returns |
| Consumes all the items and returns the underlying vector. Order of items is arbitrary. |
| Returns an iterator over all values. Order is undefined. |
| Returns the number of elements. |
| Creates a new binary heap. |
| Returns a reference to the greatest item. |
| Removes and returns the greatest item. |
| Pushes a new value. |
29.3.1Creating a new instanceΒΆ
To create a new binary heap BinaryHeap<V>, an easy way, like for the
Vec type, is to let the compiler infer the type. Inserting
at least one value will give the compiler the information it needs:
use std::collections::BinaryHeap;
let mut values = BinaryHeap::new();
values.push(10);
values.push(24);
valuesCouldn't automatically determine type of variable `values`.
Please give it an explicit type.Note that objects moved into the set are either copied or moved, depending on their type.
A BinaryHeap may also be created from a vector or an array:
let mut other_values = BinaryHeap::from([50, 4, 73, 87, 56, 33, 15]);
other_values29.3.2Merging two heapsΒΆ
Using the append() method, we can move all the items of a heap into
another:
values.append(&mut other_values);
values29.3.3Max valueΒΆ
The max value is at the root node. To look at it we use the peek()
method:
values.peek()If we remove it with pop():
values.pop()The heap is re-arranged:
values