Created
March 18, 2021 02:01
-
-
Save jakerieger/4d9c18f13d0ccb7f6e8d9bce9b092cb8 to your computer and use it in GitHub Desktop.
Binary Search
This file contains hidden or 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
/** | |
** -- Assumes a storted list (ascending) as input | |
**/ | |
function binarySearch(inputArray, token) { | |
if (token > inputArray[inputArray.length - 1]) { | |
console.log('Not found'); | |
return; | |
} | |
if (token < inputArray[0]) { | |
console.log('Not found'); | |
return; | |
} | |
if (inputArray.length === 0) { | |
console.log('Not found'); | |
return; | |
} | |
const arrLength = inputArray.length; | |
var index = (arrLength/2) | 0; | |
if (inputArray[index] === token) { | |
console.log('Found'); | |
return; | |
} | |
if (token > inputArray[index]) | |
inputArray = inputArray.splice(-index); | |
if (token < inputArray[index]) | |
inputArray = inputArray.splice(0, index) | |
binarySearch(inputArray, token); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment