Skip to content

Commit 57cbb74

Browse files
authored
Optimize and improve dispatch to sort* (#303)
1 parent 996902a commit 57cbb74

File tree

1 file changed

+10
-10
lines changed

1 file changed

+10
-10
lines changed

src/sparsevector.jl

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
### Common definitions
44

5-
import Base: sort, findall, copy!
5+
import Base: sort!, findall, copy!
66
import LinearAlgebra: promote_to_array_type, promote_to_arrays_
77
using LinearAlgebra: _SpecialArrays, _DenseConcatGroup
88

@@ -2123,15 +2123,15 @@ function _densifystarttolastnz!(x::SparseVector)
21232123
end
21242124

21252125
#sorting
2126-
function sort(x::AbstractCompressedVector{Tv,Ti}; kws...) where {Tv,Ti}
2127-
allvals = push!(copy(nonzeros(x)),zero(Tv))
2128-
sinds = sortperm(allvals;kws...)
2129-
n,k = length(x),length(allvals)
2130-
z = findfirst(isequal(k),sinds)::Int
2131-
newnzind = Vector{Ti}(1:k-1)
2132-
newnzind[z:end] .+= n-k+1
2133-
newnzvals = allvals[deleteat!(sinds[1:k],z)]
2134-
typeof(x)(n,newnzind,newnzvals)
2126+
function sort!(x::AbstractCompressedVector; kws...)
2127+
nz = nonzeros(x)
2128+
sort!(nz; kws...)
2129+
i = searchsortedfirst(nz, zero(eltype(x)); kws...)
2130+
I = nonzeroinds(x)
2131+
Base.require_one_based_indexing(x, nz, I)
2132+
I[1:i-1] .= 1:i-1
2133+
I[i:end] .= i+length(x)-length(nz):length(x)
2134+
x
21352135
end
21362136

21372137
function fkeep!(f, x::AbstractCompressedVector{Tv}) where Tv

0 commit comments

Comments
 (0)