binarySearch
external fun binarySearch(array: ReadonlyArray<Any>, itemToFind: Any, comparator: binarySearchComparator): Int(source)
Finds an item in a sorted array.
// Create a comparator function to search through an array of numbers.
function comparator(a, b) {
return a - b;
};
const numbers = [0, 2, 4, 6, 8];
const index = binarySearch(numbers, 6, comparator); // 3
Content copied to clipboard
Return
The index of itemToFind
in the array, if it exists. If itemToFind
does not exist, the return value is a negative number which is the bitwise complement (~) of the index before which the itemToFind should be inserted in order to maintain the sorted order of the array.
Parameters
array
The sorted array to search.
itemToFind
The item to find in the array.
comparator
The function to use to compare the item to elements in the array.