Searches an ascending array and returns the index of the first copy of a value, or of the nearest smaller item.
When the value is present, the lowest index holding it is returned. When it is absent, the result is the index of the closest item below it, which is where a lower neighbour sits.
If every item is larger than the value, the result is -1. The array has to be sorted ascending.
Syntax
array.binary_search_leftmost(id: array<int/float>, val: series int/float) -> series int
array.binary_search_leftmost(id: any array type, val: series int/float/string, sort_field: const int/string (optional)) -> series int
array.binary_search_leftmost(val: series int/float) -> series int
array.binary_search_leftmost(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. |
| val | series int/ | required | The value to look for. If it is missing, the index of the nearest smaller item comes back. |
| 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 first match, or of the nearest lower item.
Example
//@version=6
indicator("array.binary_search_leftmost: level below", overlay = false)
var levels = array.from(10.0, 20.0, 20.0, 30.0)
plot(array.binary_search_leftmost(levels, 20.0), "Value present")
plot(array.binary_search_leftmost(levels, 25.0), "Value absent")See also
Runs on Sidechair