JuliaLang/julia — pull request #1008 by tshort (2012-07-05 17:12:19+00:00)
Title: Add searchsortedfirst and searchsortedlast.

The existing searchsorted is a little inconsistent for vectors with duplicate items. I've added two new functions for finding first and last elements when duplicates are present:

```jl
function searchsortedlast(a::Vector, x)
## Index of the last value of vector a that is less than or equal to x.
## Returns 0 if x is less than all values of a.

function searchsortedfirst(a::Vector, x)
## Index of the first value of vector a that is greater than or equal to x.
## Returns length(a) + 1 if x is greater than all values in a.
```

The existing searchsorted is closest to searchsortedlast.

Here is a comparison with searchsorted:

```jl
julia> searchsorted([1., 1, 2, 2, 3, 3], 0)
1

julia> searchsorted([1., 1, 2, 2, 3, 3], 1)
2

julia> searchsorted([1., 1, 2, 2, 3, 3], 2)
4

julia> searchsorted([1., 1, 2, 2, 3, 3], 2.5)
5

julia> searchsorted([1., 1, 2, 2, 3, 3], 3) # inconsistent; 6 expected
5

julia> searchsorted([1., 1, 2, 2, 3, 3], 4)
7

julia>

julia> searchsortedfirst([1., 1, 2, 2, 3, 3], 0)
1

julia> searchsortedfirst([1., 1, 2, 2, 3, 3], 1)
1

julia> searchsortedfirst([1., 1, 2, 2, 3, 3], 2)
3

julia> searchsortedfirst([1., 1, 2, 2, 3, 3], 2.5)
5

julia> searchsortedfirst([1., 1, 2, 2, 3, 3], 3)
5

julia> searchsortedfirst([1., 1, 2, 2, 3, 3], 4)
7

julia>

julia> searchsortedlast([1., 1, 2, 2, 3, 3], 0)
0

julia> searchsortedlast([1., 1, 2, 2, 3, 3], 1)
2

julia> searchsortedlast([1., 1, 2, 2, 3, 3], 2)
4

julia> searchsortedlast([1., 1, 2, 2, 3, 3], 2.5)
4

julia> searchsortedlast([1., 1, 2, 2, 3, 3], 3)
6

julia> searchsortedlast([1., 1, 2, 2, 3, 3], 4)
6
```