searchsortedlast
searchsortedlast(a, x, [by=
Returns the index of the last value in a less than or equal to x, according to the specified order. Returns 0 if x is less than all values in a.
Examples
In the Julia programming language, the function searchsortedlast(a, x, [by=<transform>,] [lt=<comparison>,] [rev=false]) is used to find the index of the last value in a that is less than or equal to x, based on the specified order. If x is less than all values in a, it returns 0. Here are some examples of how to use this function:
-
Find the last value less than or equal to a given number:
julia> arr = [1, 3, 5, 7, 9]; julia> searchsortedlast(arr, 6) 3In this example, the function returns the index
3since it is the last index where the value is less than or equal to6. -
Use a custom comparison function:
julia> arr = ["apple", "banana", "grape", "orange"]; julia> searchsortedlast(arr, "pear", lt = (a, b) -> length(a) < length(b)) 2Here, the function uses a custom comparison function to determine the order based on the length of the strings. It returns the index
2since it is the last index where the length of the value is less than the length of"pear". - Perform a reverse search:
julia> arr = [5, 4, 3, 2, 1]; julia> searchsortedlast(arr, 3, rev = true) 3In this example, the function performs a reverse search and returns the index
3since it is the last index where the value is less than or equal to3in the reversed array.
Common mistake example:
julia> arr = [1, 3, 5, 7, 9];
julia> searchsortedlast(arr, 10)
0
In this example, the value 10 is greater than all the values in the array arr. Therefore, the function returns 0 as specified in the function's behavior when x is less than all values in a.
See Also
find, findfirst, findin, findlast, findmin, findn, findnext, findnz, findprev, rsearch, rsearchindex, searchsorted, searchsortedfirst, searchsortedlast, sort, sort!, sortcols, sortperm, sortperm!,User Contributed Notes
Add a Note
The format of note supported is markdown, use triple backtick to start and end a code block.