From db570dfb8d7607d98e71d092a2933a44bf4e3f55 Mon Sep 17 00:00:00 2001 From: Lilith Orion Hafner Date: Tue, 19 Jul 2022 11:05:30 -0400 Subject: [PATCH] Stop using view in adaptive sort (#45699) --- base/sort.jl | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/base/sort.jl b/base/sort.jl index 0eb2ae8a5b4be..35d7d7344d59d 100644 --- a/base/sort.jl +++ b/base/sort.jl @@ -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: >>>, !== @@ -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! @@ -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