Created
February 26, 2019 12:56
-
-
Save okovalov/72634b435c237ff0f26a43b1abd9e027 to your computer and use it in GitHub Desktop.
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
const binarySearch = (arr, key) => { | |
const midIdx = Math.floor(arr.length / 2) | |
const midElement = arr[midIdx] | |
if (midElement === key) return true | |
if (arr.length === 1) return false | |
if (midElement > key) { | |
return binarySearch(arr.splice(0, midIdx), key) | |
} | |
if (midElement < key) { | |
return binarySearch(arr.splice(midIdx, arr.length), key) | |
} | |
return false | |
} | |
const arr = [1, 3, 5, 6, 8, 12, 23, 55, 90, 98] | |
console.log(binarySearch([...arr], 91)) // false | |
console.log(binarySearch([...arr], 23)) // true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment