Skip to content

Commit

Permalink
fix searchsorted for sorted segments of arrays
Browse files Browse the repository at this point in the history
  • Loading branch information
tanmaykm committed Jul 9, 2014
1 parent 2b6d708 commit e0dd47d
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 6 deletions.
12 changes: 6 additions & 6 deletions base/sort.jl
Original file line number Diff line number Diff line change
Expand Up @@ -159,19 +159,19 @@ end
# returns the range of indices of v equal to x
# if v does not contain x, returns a 0-length range
# indicating the insertion point of x
function searchsorted(v::AbstractVector, x, lo::Int, hi::Int, o::Ordering)
1 <= lo <= hi <= length(v) || throw(BoundsError())
lo = lo-1
hi = hi+1
function searchsorted(v::AbstractVector, x, ilo::Int, ihi::Int, o::Ordering)
1 <= ilo <= ihi <= length(v) || throw(BoundsError())
lo = ilo-1
hi = ihi+1
@inbounds while lo < hi-1
m = (lo+hi)>>>1
if lt(o, v[m], x)
lo = m
elseif lt(o, x, v[m])
hi = m
else
a = searchsortedfirst(v, x, max(lo,1), m, o)
b = searchsortedlast(v, x, m, min(hi,length(v)), o)
a = searchsortedfirst(v, x, max(lo,ilo), m, o)
b = searchsortedlast(v, x, m, min(hi,ihi), o)
return a:b
end
end
Expand Down
2 changes: 2 additions & 0 deletions test/sorting.jl
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ end

@test searchsorted([1:10], 1, by=(x -> x >= 5)) == 1:4
@test searchsorted([1:10], 10, by=(x -> x >= 5)) == 5:10
@test searchsorted([1:5, 1:5, 1:5], 1, 6, 10, Base.Order.Forward) == 6:6
@test searchsorted(ones(15), 1, 6, 10, Base.Order.Forward) == 6:10

for (rg,I) in {(49:57,47:59), (1:2:17,-1:19), (-3:0.5:2,-5:.5:4)}
rg_r = reverse(rg)
Expand Down

0 comments on commit e0dd47d

Please sign in to comment.