compareFn: A comparison function to determine the order.
isSorted: Whether the array is pre-sorted (defaults to false).
Returns number
The index of the target in the array, or -1 if not found.
Example
// Basic usage with an array of numbers constdata = [4, 2, 7, 1]; constconfig = { compareFn: (a, b) =>a - b, isSorted:false }; constindex = binarySearch(data, 7, config); // index would be 3 after sorting
Example
// Usage with strings in alphabetical order constdata = ['apple', 'banana', 'cherry']; constconfig = { compareFn: (a, b) =>a.localeCompare(b), isSorted:true }; constindex = binarySearch(data, 'banana', config); // index would be 1
Performs a binary search on an array with a custom comparison function.
isSorted
isfalse
, the array will be sorted using TimSort.compareFn
.