Skip to content

Instantly share code, notes, and snippets.

@ricokareem
Last active July 15, 2017 18:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ricokareem/b925044e005e167ef07ef1597fc54832 to your computer and use it in GitHub Desktop.
Save ricokareem/b925044e005e167ef07ef1597fc54832 to your computer and use it in GitHub Desktop.
JS Bin[binary search algo]// source http://jsbin.com/koluho
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