Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions docs/src/heaps.md
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,10 @@ array without sorting the entire array first:
```julia
nlargest(3, [0,21,-12,68,-25,14]) # => [68,21,14]
nsmallest(3, [0,21,-12,68,-25,14]) # => [-25,-12,0]
nlargest(3, [0,21,-12,68,-25,14], by=abs) # => [68,-25,21]
```

`nlargest(n, a)` is equivalent to `sort(a, lt = >)[1:min(n, end)]`, and
`nsmallest(n, a)` is equivalent to `sort(a, lt = <)[1:min(n, end)]`.
Both functions support the same `lt`, `by`, and `order` keyword arguments as
`sort` to define how elements are ordered.
`nsmallest(n, a; kw...)` is equivalent to `sort(a; kw...)[1:min(n, end)]`, and
`nlargest(n, a; kw...)` is equivalent to `sort(a; rev=true, kw...)[1:min(n, end)]`.
50 changes: 27 additions & 23 deletions src/heaps.jl
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,10 @@
#
###########################################################


import Base.Order: Ordering, lt, Forward, Reverse, ord


# HT: handle type
# VT: value type

Expand All @@ -55,17 +59,6 @@ abstract type AbstractMutableHeap{VT,HT} <: AbstractHeap{VT} end

abstract type AbstractMinMaxHeap{VT} <: AbstractHeap{VT} end

# comparer

struct LessThan
end

struct GreaterThan
end

compare(c::LessThan, x, y) = x < y
compare(c::GreaterThan, x, y) = x > y

# heap implementations

include("heaps/binary_heap.jl")
Expand Down Expand Up @@ -97,14 +90,15 @@ end

# Array functions using heaps

function nextreme(comp::Comp, n::Int, arr::AbstractVector{T}) where {T, Comp}
function nextreme(order::Ordering, n::Int, arr::AbstractVector{T}) where {T}
if n <= 0
return T[] # sort(arr)[1:n] returns [] for n <= 0
elseif n >= length(arr)
return sort(arr, lt = (x, y) -> compare(comp, y, x))
return sort(arr, order=order)
end

buffer = BinaryHeap{T,Comp}()
# We want the top of the heap to be the "largest" element according to the order
buffer = BinaryHeap{T}(ReverseOrdering(order))

for i = 1 : n
@inbounds xi = arr[i]
Expand All @@ -113,7 +107,7 @@ function nextreme(comp::Comp, n::Int, arr::AbstractVector{T}) where {T, Comp}

for i = n + 1 : length(arr)
@inbounds xi = arr[i]
if compare(comp, top(buffer), xi)
if lt(order, xi, top(buffer))
# This could use a pushpop method
pop!(buffer)
push!(buffer, xi)
Expand All @@ -124,23 +118,33 @@ function nextreme(comp::Comp, n::Int, arr::AbstractVector{T}) where {T, Comp}
end

"""
nlargest(n, arr)
nlargest(n, arr; kw...)

Return the `n` largest elements of the array `arr`.

Equivalent to `sort(arr, lt = >)[1:min(n, end)]`
Equivalent to `sort(arr; kw...)[1:min(n, end)]`
"""
function nlargest(n::Int, arr::AbstractVector{T}) where T
return nextreme(LessThan(), n, arr)
function nlargest(n::Int, arr::AbstractVector{T};
lt=isless, by=identity, order::Ordering=Forward) where T
nlargest(n, arr, ord(lt, by, nothing, order))
end

function nlargest(n::Int, arr::AbstractVector{T}, order::Ordering) where T
return nextreme(ReverseOrdering(order), n, arr)
end

"""
nsmallest(n, arr)
nsmallest(n, arr; kw...)

Return the `n` smallest elements of the array `arr`.

Equivalent to `sort(arr, lt = <)[1:min(n, end)]`
Equivalent to `sort(arr; rev=true, kw...)[1:min(n, end)]`
"""
function nsmallest(n::Int, arr::AbstractVector{T}) where T
return nextreme(GreaterThan(), n, arr)
function nsmallest(n::Int, arr::AbstractVector{T};
lt=isless, by=identity, order::Ordering=Forward) where T
nsmallest(n, arr, ord(lt, by, nothing, order))
end

function nsmallest(n::Int, arr::AbstractVector{T}, order::Ordering) where T
return nextreme(order, n, arr)
end
2 changes: 0 additions & 2 deletions src/heaps/arrays_as_heaps.jl
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
# This contains code that was formerly a part of Julia. License is MIT: http://julialang.org/license

import Base.Order: Forward, Ordering, lt


# Heap operations on flat arrays
# ------------------------------
Expand Down
55 changes: 34 additions & 21 deletions src/heaps/binary_heap.jl
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,15 @@
#
#################################################

function _heap_bubble_up!(comp::Comp, valtree::Array{T}, i::Int) where {Comp,T}
function _heap_bubble_up!(order::Ordering, valtree::Array{T}, i::Int) where {T}
i0::Int = i
@inbounds v = valtree[i]

while i > 1 # nd is not root
p = i >> 1
@inbounds vp = valtree[p]

if compare(comp, v, vp)
if lt(order, v, vp)
# move parent downward
@inbounds valtree[i] = vp
i = p
Expand All @@ -28,7 +28,7 @@ function _heap_bubble_up!(comp::Comp, valtree::Array{T}, i::Int) where {Comp,T}
end
end

function _heap_bubble_down!(comp::Comp, valtree::Array{T}, i::Int) where {Comp,T}
function _heap_bubble_down!(order::Ordering, valtree::Array{T}, i::Int) where {T}
@inbounds v::T = valtree[i]
swapped = true
n = length(valtree)
Expand All @@ -40,15 +40,15 @@ function _heap_bubble_down!(comp::Comp, valtree::Array{T}, i::Int) where {Comp,T
rc = lc + 1
@inbounds lv = valtree[lc]
@inbounds rv = valtree[rc]
if compare(comp, rv, lv)
if compare(comp, rv, v)
if lt(order, rv, lv)
if lt(order, rv, v)
@inbounds valtree[i] = rv
i = rc
else
swapped = false
end
else
if compare(comp, lv, v)
if lt(order, lv, v)
@inbounds valtree[i] = lv
i = lc
else
Expand All @@ -57,7 +57,7 @@ function _heap_bubble_down!(comp::Comp, valtree::Array{T}, i::Int) where {Comp,T
end
else # contains only left child
@inbounds lv = valtree[lc]
if compare(comp, lv, v)
if lt(order, lv, v)
@inbounds valtree[i] = lv
i = lc
else
Expand All @@ -70,7 +70,7 @@ function _heap_bubble_down!(comp::Comp, valtree::Array{T}, i::Int) where {Comp,T
end


function _binary_heap_pop!(comp::Comp, valtree::Array{T}) where {Comp,T}
function _binary_heap_pop!(order::Ordering, valtree::Array{T}) where {T}
# extract root
v = valtree[1]

Expand All @@ -79,18 +79,18 @@ function _binary_heap_pop!(comp::Comp, valtree::Array{T}) where {Comp,T}
else
valtree[1] = pop!(valtree)
if length(valtree) > 1
_heap_bubble_down!(comp, valtree, 1)
_heap_bubble_down!(order, valtree, 1)
end
end
return v
end


function _make_binary_heap(comp::Comp, ty::Type{T}, xs) where {Comp,T}
function _make_binary_heap(order::Ordering, ty::Type{T}, xs) where {T}
n = length(xs)
valtree = copy(xs)
for i = 2 : n
_heap_bubble_up!(comp, valtree, i)
_heap_bubble_up!(order, valtree, i)
end
return valtree
end
Expand All @@ -102,21 +102,34 @@ end
#
#################################################

mutable struct BinaryHeap{T,Comp} <: AbstractHeap{T}
comparer::Comp
mutable struct BinaryHeap{T,O<:Ordering} <: AbstractHeap{T}
order::O
valtree::Vector{T}

BinaryHeap{T,Comp}() where {T,Comp} = new{T,Comp}(Comp(), Vector{T}())
BinaryHeap{T}(order::O) where {T,O<:Ordering} = new{T,O}(order, Vector{T}())

function BinaryHeap{T,Comp}(xs::AbstractVector{T}) where {T,Comp}
valtree = _make_binary_heap(Comp(), T, xs)
new{T,Comp}(Comp(), valtree)
function BinaryHeap{T}(order::O, xs::AbstractVector{T}) where {T,O<:Ordering}
valtree = _make_binary_heap(order, T, xs)
new{T,O}(order, valtree)
end
end

const BinaryMinHeap{T} = BinaryHeap{T, LessThan}
const BinaryMaxHeap{T} = BinaryHeap{T, GreaterThan}
BinaryHeap(order::Ordering, xs::AbstractVector{T}) where T = BinaryHeap{T}(order, xs)

function BinaryHeap{T}(xs::AbstractVector{T};
lt=isless, by=identity, rev::Union{Bool, Nothing}=nothing, order::Ordering=Forward) where T
BinaryHeap{T}(ord(lt, by, rev, order), xs)
end
BinaryHeap(xs::AbstractVector{T}; kw...) where T = BinaryHeap{T}(xs; kw...)
BinaryHeap{T}(; kw...) where T = BinaryHeap{T}(Vector{T}(); kw...)

const BinaryMinHeap{T} = BinaryHeap{T, typeof(Forward)}
const BinaryMaxHeap{T} = BinaryHeap{T, typeof(Reverse)}

BinaryMinHeap{T}() where T = BinaryHeap{T}(Forward)
BinaryMinHeap{T}(xs::AbstractVector{T}) where T = BinaryHeap{T}(Forward, xs)
BinaryMaxHeap{T}() where T = BinaryHeap{T}(Reverse)
BinaryMaxHeap{T}(xs::AbstractVector{T}) where T = BinaryHeap{T}(Reverse, xs)
BinaryMinHeap(xs::AbstractVector{T}) where T = BinaryMinHeap{T}(xs)
BinaryMaxHeap(xs::AbstractVector{T}) where T = BinaryMaxHeap{T}(xs)

Expand All @@ -134,7 +147,7 @@ isempty(h::BinaryHeap) = isempty(h.valtree)
function push!(h::BinaryHeap, v)
valtree = h.valtree
push!(valtree, v)
_heap_bubble_up!(h.comparer, valtree, length(valtree))
_heap_bubble_up!(h.order, valtree, length(valtree))
return h
end

Expand All @@ -150,4 +163,4 @@ Returns the element at the top of the heap `h`.
"""
@inline top(h::BinaryHeap) = h.valtree[1]

pop!(h::BinaryHeap{T}) where {T} = _binary_heap_pop!(h.comparer, h.valtree)
pop!(h::BinaryHeap{T}) where {T} = _binary_heap_pop!(h.order, h.valtree)
Loading