Skip to content

Instantly share code, notes, and snippets.

@bmvakili
Last active August 29, 2015 14:13
Show Gist options
  • Save bmvakili/11948091fe0565321fe3 to your computer and use it in GitHub Desktop.
Save bmvakili/11948091fe0565321fe3 to your computer and use it in GitHub Desktop.
binary search javascript
/**
* binarySearch
* efficiently searching a sorted list
* list - array of values sorted in ascending order
* value - the target value to search for
* @author Bijan Vakili
*/
function binarySearch(list, value) {
var found = -1,
delta = Math.floor(list.length / 2),
index = delta,
curr = list[index],
iteration = 0,
maxIteration = 2 + Math.round(Math.log2(list.length));
while (curr && (found == -1) && iteration < maxIteration) {
iteration++;
delta = Math.round(Math.max(1, delta / 2));
if (curr == value) {
found = index;
} else if (value < curr) {
index = index - delta;
index = Math.max(0, index);
} else if (value > curr) {
index = index + delta;
index = Math.min(list.length -1, index);
}
curr = list[index];
}
return found;
}
/********* Begin Test Code **********/
var testList = [];
var errors = 0;
function search(list, value) {
for (i = 0; i < list.length; i++) {
if (value == list[i]) {
return i;
}
}
return -1;
}
function logIt(x) {
$("#result").append(x + "<br />");
// console.log(x);
}
for (j = 0; j < 1000; j++ ) {
if (errors) {
break;
}
logIt("j " + j);
testList = [];
c = 0;
for (i = 0; i < j; i++) {
c += Math.max(1, Math.floor(Math.random()*10));
testList.push(c);
}
for (b = 0; b < testList.length + 10; b++) {
if (b > testList.length - 1) {
searchTarget = Math.floor(Math.random() * 100 + 10);
} else {
searchTarget = testList[b];
}
// logIt("calling binary search");
result = binarySearch(testList, searchTarget);
// logIt("calling search");
actual = search(testList, searchTarget);
if (result != actual) {
logIt("error");
debug = "testList = [";
for (k = 0; k < testList.length; k++) {
debug += testList[k] + ", ";
}
debug += "]";
logIt(debug);
logIt("target = " + searchTarget + ";")
errors = 1;
break;
}
}
}
logIt("done");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment