Looks up a value in an array sorted from low to high and returns its index, or -1 when it is missing.
The array must already be in ascending order. Each step discards half of what is left, so the search stays fast on long arrays. On an unsorted array the answer is not meaningful.
When the value occurs more than once, any matching index may come back. Use array.binary_search_leftmost() or array.binary_search_rightmost() when you need the first or the last copy.
Syntax
array.binary_search(id: array<int/float>, val: series int/float) -> series int
array.binary_search(id: any array type, val: series int/float/string, sort_field: const int/string (optional)) -> series int
array.binary_search(val: series int/float) -> series int
array.binary_search(val: series int/float/string, sort_field: const int/string (optional)) -> series intArguments
| Name | Type | Default | Description |
|---|---|---|---|
| id | array<int/ | required | The array to search. It must already be sorted from low to high, or the answer is meaningless. |
| val | series int/ | required | The value to look for. The call returns its index, or -1 when it is not in the array. |
| sort_field | const int/ | na | The field of a user-defined type to sort by when the array holds objects. |
Returns
series int: The index of the value, or -1.
Example
//@version=6
indicator("array.binary_search: seen close", overlay = false)
var closes = array.from(1.0, 5.0, 9.0)
hit = array.binary_search(closes, 5.0)
plot(hit, "Index of 5.0")
plot(array.binary_search(closes, 7.0), "Index of 7.0")See also
Runs on Sidechair