Skip to content

Instantly share code, notes, and snippets.

@aaronmcadam
Created September 28, 2016 22:06
Show Gist options
  • Save aaronmcadam/ac18bec52aa350e2a262ee3dd6608aec to your computer and use it in GitHub Desktop.
Save aaronmcadam/ac18bec52aa350e2a262ee3dd6608aec to your computer and use it in GitHub Desktop.
test('binary search returns true if the value exists in middle', t => {
const list = [1, 2, 3, 4, 5, 6, 7];
const target = 4;
t.is(binarySearch(list, target), 4);
});
test('binary search returns true if the value exists in upper half', t => {
const list = [1, 2, 3, 4, 5, 6, 7];
const target = 6;
t.is(binarySearch(list, target), 6);
});
test('binary search returns true if the value exists in lower half', t => {
const list = [1, 2, 3, 4, 5, 6, 7];
const target = 3;
t.is(binarySearch(list, target), 3);
});
const binarySearch = (list, target) => {
const midpoint = Math.floor(list.length / 2);
if (list[midpoint] === target) {
return list[midpoint];
} else if (list[midpoint] < target && list.length > 1) {
return binarySearch(list.splice(midpoint, Number.MAX_VALUE), target);
} else if (list[midpoint] > target && list.length > target) {
return binarySearch(list.splice(0, midpoint), target);
} else {
return -1;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment