Skip to content

Commit 7bd73b6

Browse files
authored
[backport #35274] fix #35272, searchsorted(3:-1:1, 2.5, rev=true) (#35435)
1 parent 44fa722 commit 7bd73b6

File tree

2 files changed

+21
-2
lines changed

2 files changed

+21
-2
lines changed

base/sort.jl

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -253,7 +253,11 @@ function searchsortedlast(a::AbstractRange{<:Integer}, x::Real, o::DirectOrderin
253253
if step(a) == 0
254254
lt(o, x, first(a)) ? 0 : length(a)
255255
else
256-
clamp( fld(floor(Integer, x) - first(a), step(a)) + 1, 0, length(a))
256+
if o isa ForwardOrdering
257+
clamp( fld(floor(Integer, x) - first(a), step(a)) + 1, 0, length(a))
258+
else
259+
clamp( fld(ceil(Integer, x) - first(a), step(a)) + 1, 0, length(a))
260+
end
257261
end
258262
end
259263

@@ -262,7 +266,11 @@ function searchsortedfirst(a::AbstractRange{<:Integer}, x::Real, o::DirectOrderi
262266
if step(a) == 0
263267
lt(o, first(a), x) ? length(a)+1 : 1
264268
else
265-
clamp(-fld(floor(Integer, -x) + first(a), step(a)) + 1, 1, length(a) + 1)
269+
if o isa ForwardOrdering
270+
clamp(-fld(floor(Integer, -x) + first(a), step(a)) + 1, 1, length(a) + 1)
271+
else
272+
clamp(-fld(ceil(Integer, -x) + first(a), step(a)) + 1, 1, length(a) + 1)
273+
end
266274
end
267275
end
268276

test/sorting.jl

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -138,6 +138,17 @@ end
138138
@test searchsortedlast(500:1.0:600, -1.0e20) == 0
139139
@test searchsortedlast(500:1.0:600, 1.0e20) == 101
140140
end
141+
@testset "issue #35272" begin
142+
for v0 = (3:-1:1, 3.0:-1.0:1.0), v = (v0, collect(v0))
143+
@test searchsorted(v, 3, rev=true) == 1:1
144+
@test searchsorted(v, 3.0, rev=true) == 1:1
145+
@test searchsorted(v, 2.5, rev=true) == 2:1
146+
@test searchsorted(v, 2, rev=true) == 2:2
147+
@test searchsorted(v, 1.2, rev=true) == 3:2
148+
@test searchsorted(v, 1, rev=true) == 3:3
149+
@test searchsorted(v, 0.1, rev=true) == 4:3
150+
end
151+
end
141152
end
142153
# exercise the codepath in searchsorted* methods for ranges that check for zero step range
143154
struct ConstantRange{T} <: AbstractRange{T}

0 commit comments

Comments
 (0)