Created
April 15, 2015 04:23
-
-
Save NotTheEconomist/cf2b57b218a4c978e82b to your computer and use it in GitHub Desktop.
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
def binary_search(needle, haystack): | |
start, end = 0, len(haystack)-1 | |
while start < end: | |
pivot_idx = (start + end) // 2 | |
pivot = haystack[pivot_idx] | |
if needle == pivot: | |
return True | |
if pivot_idx == start: | |
# edge case -- I'm sure a better algorithm | |
# would write this into the while condition | |
break | |
if needle < pivot: | |
end = pivot_idx | |
else: | |
start = pivot_idx | |
return False |
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
import unittest | |
from main import binary_search | |
class Tester(unittest.TestCase): | |
def test_sorted_lists(self): | |
true_cases = [(3, [1, 3, 4, 5, 6, 7]), | |
("s", ['a','b','s','q'])] | |
false_cases = [(2, [1, 3, 4, 5, 6, 7]), | |
('something', ['a', 'list', 'of', 'test', 'values'])] | |
for case in true_cases: | |
needle, haystack = case | |
self.assertTrue(binary_search(needle, haystack)) | |
for case in false_cases: | |
needle, haystack = case | |
self.assertFalse(binary_search(needle, haystack)) | |
def test_unsorted_list(self): | |
test_case = [('something', ['an', 'unsorted', 'list'])] | |
for case in test_case: | |
needle, haystack = case | |
self.assertFalse(binary_search(needle, haystack)) | |
if __name__ == "__main__": | |
unittest.main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment