From 429457db94cf933c3c6fa1337449e03c15a2df40 Mon Sep 17 00:00:00 2001 From: Rafael Fourquet Date: Sat, 11 Apr 2020 14:08:12 +0200 Subject: [PATCH] [backport #35274] fix #35272, searchsorted(3:-1:1, 2.5, rev=true) --- base/sort.jl | 12 ++++++++++-- test/sorting.jl | 11 +++++++++++ 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/base/sort.jl b/base/sort.jl index 8d7bfba5a0093..bd5b9e499f8c6 100644 --- a/base/sort.jl +++ b/base/sort.jl @@ -253,7 +253,11 @@ function searchsortedlast(a::AbstractRange{<:Integer}, x::Real, o::DirectOrderin if step(a) == 0 lt(o, x, first(a)) ? 0 : length(a) else - clamp( fld(floor(Integer, x) - first(a), step(a)) + 1, 0, length(a)) + if o isa ForwardOrdering + clamp( fld(floor(Integer, x) - first(a), step(a)) + 1, 0, length(a)) + else + clamp( fld(ceil(Integer, x) - first(a), step(a)) + 1, 0, length(a)) + end end end @@ -262,7 +266,11 @@ function searchsortedfirst(a::AbstractRange{<:Integer}, x::Real, o::DirectOrderi if step(a) == 0 lt(o, first(a), x) ? length(a)+1 : 1 else - clamp(-fld(floor(Integer, -x) + first(a), step(a)) + 1, 1, length(a) + 1) + if o isa ForwardOrdering + clamp(-fld(floor(Integer, -x) + first(a), step(a)) + 1, 1, length(a) + 1) + else + clamp(-fld(ceil(Integer, -x) + first(a), step(a)) + 1, 1, length(a) + 1) + end end end diff --git a/test/sorting.jl b/test/sorting.jl index 57c70f3105aa5..715662356a8f0 100644 --- a/test/sorting.jl +++ b/test/sorting.jl @@ -138,6 +138,17 @@ end @test searchsortedlast(500:1.0:600, -1.0e20) == 0 @test searchsortedlast(500:1.0:600, 1.0e20) == 101 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}