Skip to content

Simplify and increase generality of sorting #397

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
13 changes: 3 additions & 10 deletions src/array.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1100,28 +1100,21 @@ function Base.Broadcast.broadcasted(::typeof(levelcode), A::CategoricalArray{T})
end
end

function Base.sort!(v::CategoricalVector;
# alg is ignored since counting sort is more efficient
alg::Base.Algorithm=Base.Sort.defalg(v),
lt=isless,
by=identity,
rev::Bool=false,
order::Base.Ordering=Base.Forward)
function Base.sort!(v::CategoricalVector; kws...)
# dispatch regardless of alg since counting sort is more efficient
counts = zeros(UInt, length(v.pool) + (eltype(v) >: Missing))

# do a count/histogram of the references
@inbounds for ref in v.refs
counts[ref + (eltype(v) >: Missing)] += 1
end

# compute the order in which to read from counts
ord = Base.Sort.ord(lt, by, rev, order)
seen = counts .> 0
anymissing = eltype(v) >: Missing && seen[1]
levs = eltype(v) >: Missing ?
eltype(v)[i == 0 ? missing : CategoricalValue(v.pool, i) for i in 0:length(v.pool)] :
eltype(v)[CategoricalValue(v.pool, i) for i in 1:length(v.pool)]
sortedlevs = sort!(Vector(view(levs, seen)), order=ord)
sortedlevs = sort!(Vector(view(levs, seen)); kws...)
levelsmap = something.(indexin(sortedlevs, levs))
j = 0
refs = v.refs
Expand Down