searchsorted

searchsorted(a, x, [by=,] [lt=,] [rev=false])

Returns the range of indices of a which compare as equal to x according to the order specified by the by, lt and rev keywords, assuming that a is already sorted in that order. Returns an empty range located at the insertion point if a does not contain values equal to x.

Examples

In the Julia programming language, the function searchsorted(a, x, [by=<transform>,] [lt=<comparison>,] [rev=false])

Returns the range of indices of a which compare as equal to x according to the order specified by the by, lt, and rev keywords, assuming that a is already sorted in that order. It returns an empty range located at the insertion point if a does not contain values equal to x.

julia> arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

julia> searchsorted(arr, 4)
4:4

julia> searchsorted(arr, 11)
11:11
  1. Search for an existing value:

    julia> arr = [10, 20, 30, 40, 50];
    julia> searchsorted(arr, 30)
    3:3

    The example above searches for the value 30 in the sorted array arr and returns the range 3:3 since it is found at index 3.

  2. Search for a missing value:

    julia> arr = [1, 2, 3, 4, 5];
    julia> searchsorted(arr, 6)
    6:6

    In this example, the value 6 is not present in the sorted array arr. The function returns the range 6:6 which represents the insertion point for the missing value.

  3. Search with custom ordering and transformation:
    julia> arr = ["apple", "banana", "cherry", "date"];
    julia> searchsorted(arr, "cherry", by=length, lt=isless)
    3:3

    The searchsorted function allows specifying custom ordering and transformation using the by and lt arguments. In this example, the array of strings arr is sorted by length and compared using isless. The function returns the range 3:3 for the value "cherry".

Common mistake example:

julia> arr = [5, 10, 15, 20];
julia> searchsorted(arr, 12)
3:3

In this example, the value 12 is not present in the sorted array arr. The function returns the range 3:3 which indicates the insertion point. It's important to check the range returned to determine if the value is found or not.

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.

*Required Field
Details

Checking you are not a robot: