Skip to content

Instantly share code, notes, and snippets.

@iamamit-107
Created May 9, 2020 16:27
Show Gist options
  • Save iamamit-107/1355d78c20ccee9ae8995a6caa567596 to your computer and use it in GitHub Desktop.
Save iamamit-107/1355d78c20ccee9ae8995a6caa567596 to your computer and use it in GitHub Desktop.
function binarySearch(arr, item) {
let startIndex = 0;
let endIndex = arr.length - 1;
while (startIndex < endIndex) {
let middleIndex = Math.floor((startIndex + endIndex) / 2);
if (arr[middleIndex] === item) {
return `Found at index ${middleIndex}`;
}
if (arr[middleIndex] < item) {
startIndex = middleIndex + 1;
} else {
endIndex = middleIndex - 1;
}
}
return "Not Found";
}
console.log(binarySearch([5, 10, 20, 30, 40], 30));
//output: Found at index 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment