Binary Search is an efficient algorithm for finding an item from a sorted list of items. It works by repeatedly dividing in half the portion of the list that could contain the item, until you've narrowed down the possible locations to just one.
def binary_search(arr, low, high, x):
while low <= high:
mid = low + (high - low) // 2
if arr[mid] == x:
return mid
elif arr[mid] < x:
low = mid + 1
else:
high = mid - 1
return -1
function binarySearch(arr, x) {
let low = 0;
let high = arr.length - 1;
while (low <= high) {
let mid = Math.floor(low + (high - low) / 2);
if (arr[mid] === x) return mid;
if (arr[mid] < x) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return -1;
}