Last active
July 15, 2017 18:48
-
-
Save ricokareem/b925044e005e167ef07ef1597fc54832 to your computer and use it in GitHub Desktop.
JS Bin[binary search algo]// source http://jsbin.com/koluho
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(data, value) { | |
while (true) { | |
var mid = parseInt(data.length/2); | |
if (value === data[mid]) { | |
return data[mid]; | |
} else if (value > data[mid]) { | |
data = data.slice(mid); | |
} else if (value < data[mid]) { | |
data = data.slice(0, mid); | |
} | |
if (mid === 0) { | |
if (value === data[0]) { | |
return data[0]; | |
} | |
return null; | |
} | |
} | |
} | |
// TEST | |
var data = []; | |
for (i=0;i<1000000;i++) {data.push(i);} | |
value = Math.random() * 10000 | 0; | |
// ES6 | |
data.find(x => x === value); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment