Created
May 9, 2020 16:27
-
-
Save iamamit-107/1355d78c20ccee9ae8995a6caa567596 to your computer and use it in GitHub Desktop.
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
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