Created
February 20, 2019 20:59
-
-
Save rook2pawn/59f2af9fdc0be4dbd851f27d07b622c5 to your computer and use it in GitHub Desktop.
binary search list
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
const list = [1,1,2,3,5,5,5,5,10,62,95,107,109,202]; | |
function search(list, num) { | |
// console.log("Searching for :", num, "LIST:", list) | |
let mid = ~~(list.length / 2); | |
let item = list[mid]; | |
if (item === num) { | |
return {isFound:true, num}; | |
} | |
if (list.length === 1) { | |
return {isFound:false, num}; | |
} | |
// console.log("LEFT HALF:", list.slice(0,mid)) | |
// console.log("RIGHT HALF:", list.slice(mid)) | |
if (item > num) { | |
return search(list.slice(0,mid), num) | |
} | |
if (item < num) { | |
return search(list.slice(mid), num); | |
} | |
} | |
console.log(search(list , 202)); | |
console.log(search(list , 62)); | |
console.log(search(list , 63)); | |
console.log(search(list , 5)); | |
console.log(search(list , 11)); | |
/* | |
{ isFound: true, num: 202 } | |
{ isFound: true, num: 62 } | |
{ isFound: false, num: 63 } | |
{ isFound: true, num: 5 } | |
{ isFound: false, num: 11 } | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment