Skip to content

Instantly share code, notes, and snippets.

@Nilesh-Saini-09
Created June 19, 2022 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Nilesh-Saini-09/f0a9416d568c30b1640c0807d76c1717 to your computer and use it in GitHub Desktop.
Save Nilesh-Saini-09/f0a9416d568c30b1640c0807d76c1717 to your computer and use it in GitHub Desktop.
Binary Search
// ES6 Arrow Function
// Iterative Binary Search
const binarySearch = (arr, x) => {
let start = 0;
let end = arr.length - 1;
let mid;
while (start <= end) {
mid = Math.floor((start + end) / 2);
if (arr[mid] === x) return mid;
if (arr[mid] < x) {
start = mid + 1;
} else {
end = mid - 1;
}
}
return -1;
}
// let testArray = [1, 2, 3, 4, 5, 6, 7, 8];
// let x = 8;
// binarySearch(testArray, x);
// output => 7
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment