-
-
Save Nilesh-Saini-09/f0a9416d568c30b1640c0807d76c1717 to your computer and use it in GitHub Desktop.
Binary Search
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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