diff --git a/base/sort.jl b/base/sort.jl index 27a71d7466574f..fa102c1eba3c50 100644 --- a/base/sort.jl +++ b/base/sort.jl @@ -262,7 +262,11 @@ function searchsortedlast(a::AbstractRange{<:Integer}, x::Real, o::DirectOrderin elseif h < 0 && x <= last(a) lastindex(a) else - fld(floor(Integer, x) - first(a), h) + 1 + if o isa ForwardOrdering + fld(floor(Integer, x) - first(a), h) + 1 + else + fld(ceil(Integer, x) - first(a), h) + 1 + end end end @@ -280,7 +284,11 @@ function searchsortedfirst(a::AbstractRange{<:Integer}, x::Real, o::DirectOrderi elseif h < 0 && x < last(a) lastindex(a) + 1 else - -fld(floor(Integer, -x) + first(a), h) + 1 + if o isa ForwardOrdering + -fld(floor(Integer, -x) + first(a), h) + 1 + else + -fld(ceil(Integer, -x) + first(a), h) + 1 + end end end diff --git a/test/sorting.jl b/test/sorting.jl index 7f4234cb679e33..37d294a6d962e3 100644 --- a/test/sorting.jl +++ b/test/sorting.jl @@ -177,6 +177,17 @@ end end end end + @testset "issue #35272" begin + for v0 = (3:-1:1, 3.0:-1.0:1.0), v = (v0, collect(v0)) + @test searchsorted(v, 3, rev=true) == 1:1 + @test searchsorted(v, 3.0, rev=true) == 1:1 + @test searchsorted(v, 2.5, rev=true) == 2:1 + @test searchsorted(v, 2, rev=true) == 2:2 + @test searchsorted(v, 1.2, rev=true) == 3:2 + @test searchsorted(v, 1, rev=true) == 3:3 + @test searchsorted(v, 0.1, rev=true) == 4:3 + end + end end # exercise the codepath in searchsorted* methods for ranges that check for zero step range struct ConstantRange{T} <: AbstractRange{T}