Find the index of an element in a sorted array using binary search with O(log n) time complexity.
Code
Algorithmslet lo = 0, hi = arr.length - 1, result = -1;
while (lo <= hi) {
const mid = Math.floor((lo + hi) / 2);
if (arr[mid] === target) { result = mid; break; }
else if (arr[mid] < target) lo = mid + 1;
else hi = mid - 1;
}
return result;Parameters
Sorted array
Element to find
Browser·fetch() may be limited by CORS
More JavaScript Snippets
Add Days to Date
Add a specified number of days to a date and return the result in ISO format.
Add Query Parameter
Add or update a query parameter in a URL string.
Array Difference
Find elements in the first array that are not present in the second array.
Array Frequencies
Count how many times each value appears in an array and return a frequency map.
Array Head
Get the first n elements of an array.
Array Intersection
Find common elements that exist in both arrays.