Skip to content

Commit

Permalink
Stop using view in adaptive sort (JuliaLang#45699)
Browse files Browse the repository at this point in the history
  • Loading branch information
LilithHafner authored and Francesco Fucci committed Aug 11, 2022
1 parent ba17a60 commit 174f0ef
Showing 1 changed file with 11 additions and 4 deletions.
15 changes: 11 additions & 4 deletions base/sort.jl
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ using .Base: copymutable, LinearIndices, length, (:), iterate, OneTo,
extrema, sub_with_overflow, add_with_overflow, oneunit, div, getindex, setindex!,
length, resize!, fill, Missing, require_one_based_indexing, keytype, UnitRange,
min, max, reinterpret, signed, unsigned, Signed, Unsigned, typemin, xor, Type, BitSigned, Val,
midpoint
midpoint, @boundscheck, checkbounds

using .Base: >>>, !==

Expand Down Expand Up @@ -761,6 +761,13 @@ function _extrema(v::AbstractVector, lo::Integer, hi::Integer, o::Ordering)
end
mn, mx
end
function _issorted(v::AbstractVector, lo::Integer, hi::Integer, o::Ordering)
@boundscheck checkbounds(v, lo:hi)
@inbounds for i in (lo+1):hi
lt(o, v[i], v[i-1]) && return false
end
true
end
function sort!(v::AbstractVector{T}, lo::Integer, hi::Integer, a::AdaptiveSort, o::Ordering,
t::Union{AbstractVector{T}, Nothing}=nothing) where T
# if the sorting task is not UIntMappable, then we can't radix sort or sort_int_range!
Expand All @@ -779,11 +786,11 @@ function sort!(v::AbstractVector{T}, lo::Integer, hi::Integer, a::AdaptiveSort,
# For most arrays, a presorted check is cheap (overhead < 5%) and for most large
# arrays it is essentially free (<1%). Insertion sort runs in a fast O(n) on presorted
# input and this guarantees presorted input will always be efficiently handled
issorted(view(v, lo:hi), o) && return v
_issorted(v, lo, hi, o) && return v

# For large arrays, a reverse-sorted check is essentially free (overhead < 1%)
if lenm1 >= 500 && issorted(view(v, lo:hi), ReverseOrdering(o))
reverse!(view(v, lo:hi))
if lenm1 >= 500 && _issorted(v, lo, hi, ReverseOrdering(o))
reverse!(v, lo, hi)
return v
end

Expand Down

0 comments on commit 174f0ef

Please sign in to comment.