Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

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:

                   β”Œβ”€β”€β”
                   β”‚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

append(&other)

Moves the elements of another heap into this heap.

clear()

Removes all elements.

is_empty()

Returns true if this set contains no elements.

into_vec()

Consumes all the items and returns the underlying vector. Order of items is arbitrary.

iter()

Returns an iterator over all values. Order is undefined.

len()

Returns the number of elements.

new()

Creates a new binary heap.

peek()

Returns a reference to the greatest item.

pop()

Removes and returns the greatest item.

push(v)

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:

Couldn'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:

29.3.2Merging two heapsΒΆ

Using the append() method, we can move all the items of a heap into another:

29.3.3Max valueΒΆ

The max value is at the root node. To look at it we use the peek() method:

If we remove it with pop():

The heap is re-arranged: