Created
February 24, 2014 16:05
-
-
Save SamuraiT/9191159 to your computer and use it in GitHub Desktop.
binary search: implements with the bisection and without any third modules.
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 bisect | |
def bisection(t, target): | |
""" | |
takes a sorted list (t) and the (target) value. | |
returns the index of the (target) value in the list (t) if there | |
is ,otherwise returns None | |
""" | |
i = bisect.bisect_left(t, target) | |
if i < len(t) and t[i] == target: | |
return i | |
else: | |
return None | |
def binary_search(t, target, lo=0, hi=None): | |
"""binary search | |
takes a sorted list (t) and the (target) value and | |
returns the index of the (target) value in the list (t) if there | |
is ,otherwise returns None | |
(lo):low | |
(hi):high | |
""" | |
if not hi: hi = len(t) | |
if not lo < hi: return None | |
i = (lo + hi) / 2 | |
if t[i] == target: | |
return i | |
if t[i] > target: | |
# left search | |
return binary_search(t, target, lo, i - 1) | |
else: | |
# right search | |
return binary_search(t, target, i + 1, hi) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment