binarySearch
Finds an item in a sorted array.
Parameters:
Name | Type | Description |
---|---|---|
array |
Array | The sorted array to search. |
itemToFind |
Object | The item to find in the array. |
comparator |
Function | The function to use to compare the item to elements in the array.
The first parameter passed to the comparator function is an item in the array, the
second is itemToFind . If the array item is less than itemToFind ,
the function should return a negative value. If it is greater, the function should return
a positive value. If the items are equal, it should return 0. |
Throws:
-
DeveloperError :
array
is required. -
DeveloperError :
toFind
is required. -
DeveloperError :
comparator
is required.
Returns:
Number
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.
Example
// Create a comparator function to search through an array of numbers. var comparator = function (a, b) { return a - b; }; var numbers = [0, 2, 4, 6, 8]; var index = binarySearch(numbers, 6, comparator); // 3