Created
September 28, 2016 22:06
-
-
Save aaronmcadam/ac18bec52aa350e2a262ee3dd6608aec to your computer and use it in GitHub Desktop.
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
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