Skip to content

Instantly share code, notes, and snippets.

@ericviana
Created June 23, 2023 15:19
Show Gist options
  • Save ericviana/d77423e4f9b9a4a79d7d23c23767d025 to your computer and use it in GitHub Desktop.
Save ericviana/d77423e4f9b9a4a79d7d23c23767d025 to your computer and use it in GitHub Desktop.
Binary Search
function binarySearch(arr, target) {
let left = 0;
let right = arr.length - 1;
while (left <= right) {
let mid = Math.floor((left + right) / 2);
if (arr[mid] === target) {
return mid;
} else if (arr[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
const array = [1, 3, 5, 7, 9];
console.log(binarySearch(array, 5)); // Output: 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment