Skip to content

Instantly share code, notes, and snippets.

@xiaohanyu
Created March 7, 2017 16:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xiaohanyu/f9642393e1c76164817f76a3cf60dc17 to your computer and use it in GitHub Desktop.
Save xiaohanyu/f9642393e1c76164817f76a3cf60dc17 to your computer and use it in GitHub Desktop.
Simple binary search with simple unit test in Python.
import unittest
def binary_search(array, t):
l = 0
h = len(array) - 1
while (l <= h):
m = (l + h) // 2
if (array[m] == t):
return m
elif (array[m] < t):
l = m + 1
else:
h = m - 1
return -1
class TestBinarySearch(unittest.TestCase):
def test_binary_search(self):
self.assertEqual(binary_search([], 3), -1)
self.assertEqual(binary_search([1, 2], 3), -1)
self.assertEqual(binary_search([1, 2, 3, 4], 3), 2)
self.assertEqual(binary_search([1, 2, 3, 4, 5], 3), 2)
self.assertEqual(binary_search([1, 2, 3, 4], 3), 2)
self.assertEqual(binary_search([1, 2, 3, 4], 1), 0)
self.assertEqual(binary_search([1, 2, 3, 4], 4), 3)
if __name__ == '__main__':
unittest.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment