Skip to content

Instantly share code, notes, and snippets.

@NotTheEconomist
Created April 15, 2015 04:23
Show Gist options
  • Save NotTheEconomist/cf2b57b218a4c978e82b to your computer and use it in GitHub Desktop.
Save NotTheEconomist/cf2b57b218a4c978e82b to your computer and use it in GitHub Desktop.
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
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