Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Merge pull request #20 from kishinmanglani/master

Corrected binary search
  • Loading branch information...
commit 348815bbbbc2e67b742f6bab5a8015a10a5d9123 2 parents 96ebe18 + 5fdabd3
@nryoung authored
View
30 algorithms/searching/binary_search.py
@@ -15,26 +15,22 @@
Psuedo Code: http://en.wikipedia.org/wiki/Binary_search
- binary_search.search(sorted_list) -> integer
- binary_search.search(sorted_list) -> False
+ binary_search.search(sorted_list, key) -> index
+ binary_search.search(sorted_list, key) -> False
"""
def search(seq, key):
- imin = 0
- imax = len(seq) - 1
-
- if imax < imin:
- return False
-
- else:
- mid = len(seq) / 2
-
- if seq[mid] > key:
- return search(seq[:mid - 1], key)
-
- elif seq[mid] < key:
- return search(seq[mid + 1:], key)
-
+ lo = 0
+ hi = len(seq)
+
+ while hi > lo:
+ mid = (lo + hi) / 2
+ print mid
+ if seq[mid] < key:
+ lo = mid + 1
+ elif seq[mid] > key:
+ hi = mid
else:
return mid
+ return False
View
16 algorithms/tests/test_searching.py
@@ -14,11 +14,23 @@ def test_binarysearch(self):
rv2 = binary_search.search(self.seq, 9)
rv3 = binary_search.search(self.seq, -1)
rv4 = binary_search.search(self.seq, 10)
+ rv5 = binary_search.search(self.seq, 4)
self.assertIs(rv1, 0)
- self.assertIs(rv2, 0)
+ self.assertIs(rv2, 9)
self.assertFalse(rv3)
self.assertFalse(rv4)
-
+ self.assertIs(rv5, 4)
+ self.seq = range(9)
+ rv1 = binary_search.search(self.seq, 0)
+ rv2 = binary_search.search(self.seq, 8)
+ rv3 = binary_search.search(self.seq, -1)
+ rv4 = binary_search.search(self.seq, 10)
+ rv5 = binary_search.search(self.seq, 4)
+ self.assertIs(rv1, 0)
+ self.assertIs(rv2, 8)
+ self.assertFalse(rv3)
+ self.assertFalse(rv4)
+ self.assertIs(rv5, 4)
class TestKMPSearch(unittest.TestCase):
"""
Please sign in to comment.
Something went wrong with that request. Please try again.