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
Using alternate orderings
Heaps can also use alternate orderings apart from the default one defined by Base.isless. This is accomplished by passing an instance of Base.Ordering as the first argument to the constructor. The top of the heap will then be the element that comes first according to this ordering.
The following example uses 2-tuples to track the index of each element in the original array, but sorts only by the data value:
data = collect(enumerate(["foo", "bar", "baz"]))
h1 = BinaryHeap(data) # Standard lexicographic ordering for tuples
first(h1) # => (1, "foo")
h2 = BinaryHeap(Base.By(last), data) # Order by 2nd element only
first(h2) # => (2, "bar")
Obtained:
julia> using DataStructures
julia> data = collect(enumerate(["foo", "bar", "baz"]))
3-element Vector{Tuple{Int64, String}}:
(1, "foo")
(2, "bar")
(3, "baz")
julia> h1 = BinaryHeap(data)
ERROR: MethodError: no method matching BinaryHeap(::Vector{Tuple{Int64, String}})
Closest candidates are:
BinaryHeap(::Base.Order.Ordering, ::AbstractVector{T}) where T at E:\ProgramFiles\Julia\.julia\packages\DataStructures\vSp4s\src\heaps\binary_heap.jl:47
Stacktrace:
[1] top-level scope
@ REPL[3]:1
using Julia 1.7.1 Windows10 (also occurs in Julia 1.6.5)
UPDATE 03 Feb 2022 What works
BinaryHeap with Base.By
Suggestion
Update documentation to reflect this.
Also it is unclear that BinaryHeap is a minheap.
So it is also unclear how to create a BinaryMaxHeap which orders on the second element of the Tuple.
changed the title [-]Heaps with Tuples broken[/-][+]docs: invalid code in usage example: single-argument `BinaryHeap` constructor call throws[/+]on Oct 4, 2026
The above is difficult to decipher. The issue is that the docs give an invalid usage example. On the page on heaps, the section "Using alternate orderings" gives a usage example that seems to have a typo.
Activity
[-]Heaps with Tuples broken[/-][+]docs: invalid code in usage example: single-argument `BinaryHeap` constructor call throws[/+]nsajko commentedon Oct 4, 2026
The above is difficult to decipher. The issue is that the docs give an invalid usage example. On the page on heaps, the section "Using alternate orderings" gives a usage example that seems to have a typo.
nsajko commentedon Oct 4, 2026
Would also be nice for DataStructures documentation to link to Julia
Base.Orderdocumentation.