Sidechair

array.binary_search()

Browse the reference

Looks up a value in an array sorted from low to high and returns its index, or -1 when it is missing.

Try it in the editor

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

Pine Script
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 int

Arguments

NameTypeDefaultDescription
idarray<int/float> or any array typerequiredThe array to search. It must already be sorted from low to high, or the answer is meaningless.
valseries int/float or series int/float/stringrequiredThe value to look for. The call returns its index, or -1 when it is not in the array.
sort_fieldconst int/stringnaThe 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

Pine ScriptLook up two values in a sorted listOpen in editor
//@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