Skip to content

Commit

Permalink
Make partialsort!() and partialsortperm!() return a view rather than …
Browse files Browse the repository at this point in the history
…a copy

Returning a copy (partially) defeats the purpose of these functions, which is
to avoid allocations.
  • Loading branch information
nalimilan committed Aug 7, 2017
1 parent 55347cd commit 61b2f49
Showing 1 changed file with 14 additions and 4 deletions.
18 changes: 14 additions & 4 deletions base/sort.jl
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,12 @@ issorted(itr;
function partialsort!(v::AbstractVector, k::Union{Int,OrdinalRange}, o::Ordering)
inds = indices(v, 1)
sort!(v, first(inds), last(inds), PartialQuickSort(k), o)
v[k]

if k isa Integer
return v[k]
else
return view(v, k)
end
end

"""
Expand Down Expand Up @@ -150,7 +155,7 @@ Variant of [`partialsort!`](@ref) which copies `v` before partially sorting it,
same thing as `partialsort!` but leaving `v` unmodified.
"""
partialsort(v::AbstractVector, k::Union{Int,OrdinalRange}; kws...) =
partialsort!(copymutable(v), k; kws...)
copy(partialsort!(copymutable(v), k; kws...))


# reference on sorted binary search:
Expand Down Expand Up @@ -681,7 +686,7 @@ that value is returned; if `k` is a range, an array of values at those indices i
Note that this is equivalent to, but more efficient than, calling `sortperm(...)[k]`.
"""
partialsortperm(v::AbstractVector, k::Union{Integer,OrdinalRange}; kwargs...) =
partialsortperm!(similar(Vector{eltype(k)}, indices(v,1)), v, k; kwargs..., initialized=false)
copy(partialsortperm!(similar(Vector{eltype(k)}, indices(v,1)), v, k; kwargs..., initialized=false))

"""
partialsortperm!(ix, v, k, [alg=<algorithm>,] [by=<transform>,] [lt=<comparison>,] [rev=false,] [initialized=false])
Expand All @@ -704,7 +709,12 @@ function partialsortperm!(ix::AbstractVector{<:Integer}, v::AbstractVector,

# do partial quicksort
sort!(ix, PartialQuickSort(k), Perm(ord(lt, by, rev, order), v))
return ix[k]

if k isa Integer
return ix[k]
else
return view(ix, k)
end
end

## sortperm: the permutation to sort an array ##
Expand Down

0 comments on commit 61b2f49

Please sign in to comment.