Last active
November 4, 2018 13:14
-
-
Save Expl4Life/9013e93ec60eae372dd2abfbc5521e2a 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
//O = logN | |
function binarySearch(sortedArray, i) { | |
const mid = Math.floor(sortedArray.length / 2); | |
if (!binarySearch.counter) { | |
binarySearch.counter = 1; | |
} else { | |
binarySearch.counter++; | |
} | |
if (sortedArray[mid] === i) { | |
// console.log('match', sortedArray[mid], i); | |
return sortedArray[mid]; | |
} else if (sortedArray[mid] < i && sortedArray.length > 1) { | |
// console.log('mid lower', sortedArray[mid], i); | |
return binarySearch(sortedArray.splice(mid, Number.MAX_VALUE), i); | |
} else if (sortedArray[mid] > i && sortedArray.length > 1) { | |
// console.log('mid higher', sortedArray[mid], i); | |
return binarySearch(sortedArray.splice(0, mid), i); | |
} else { | |
// console.log('not here', i); | |
return -1; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment