Skip to content

Commit

Permalink
Add support for ranges with step 0 in searchsortedfirst and searchsor…
Browse files Browse the repository at this point in the history
…tedlast.
  • Loading branch information
GunnarFarneback committed May 15, 2013
1 parent 37101e8 commit 8dcde3f
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 8 deletions.
22 changes: 14 additions & 8 deletions base/sort.jl
Original file line number Diff line number Diff line change
Expand Up @@ -178,14 +178,20 @@ for s in {:searchsortedfirst, :searchsortedlast, :searchsorted}
end
end

searchsortedlast{T <: Real}(a::Ranges{T}, x::Real, o::Ordering) = searchsortedlast(a, x)
searchsortedlast{T <: Real}(a::Ranges{T}, x::Real) = max(min(int(fld(x - first(a), step(a))) + 1, length(a)), 0)

searchsortedfirst{T <: Real}(a::Ranges{T}, x::Real, o::Ordering) = searchsortedfirst(a, x)
function searchsortedfirst{T <: Real}(a::Ranges{T}, x::Real)
n = x - first(a)
s = step(a)
max(min(int(fld(n, s)) + (rem(n, s) != 0), length(a)), 0) + 1
function searchsortedlast{T <: Real}(a::Ranges{T}, x::Real, o::Ordering=Forward)
if step(a) == 0
lt(o, x, first(a)) ? 0 : length(a)
else
max(min(int(fld(x - first(a), step(a))) + 1, length(a)), 0)
end
end

function searchsortedfirst{T <: Real}(a::Ranges{T}, x::Real, o::Ordering=Forward)
if step(a) == 0
lt(o, first(a), x) ? length(a) + 1 : 1
else
max(min(int(-fld(first(a) - x, step(a))), length(a)), 0) + 1
end
end

searchsorted{T <: Real}(a::Ranges{T}, x::Real) = searchsortedfirst(a,x):searchsortedlast(a,x)
Expand Down
11 changes: 11 additions & 0 deletions test/sorting.jl
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,17 @@ for i = -5:.5:4
searchsortedlast(rgv_r, i, Sort.Reverse)
end

rg = 3+0*(1:5); rgv = [rg]
rg_r = rg; rgv_r = [rg_r]
for i = 2:4
@test searchsortedfirst(rg, i) == searchsortedfirst(rgv, i)
@test searchsortedlast(rg, i) == searchsortedlast(rgv, i)
@test searchsortedfirst(rg_r, i, Sort.Reverse) ==
searchsortedfirst(rgv_r, i, Sort.Reverse)
@test searchsortedlast(rg_r, i, Sort.Reverse) ==
searchsortedlast(rgv_r, i, Sort.Reverse)
end

a = rand(1:10000, 1000)

for alg in [InsertionSort, MergeSort, TimSort]
Expand Down

0 comments on commit 8dcde3f

Please sign in to comment.