Created
March 4, 2017 05:09
-
-
Save sonus21/9999879904bb5305880fe4188072fbc9 to your computer and use it in GitHub Desktop.
Generic Binary Search in Python
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(values, key, lo=0, hi=None, length=None, comp=None): | |
""" | |
This is a binary search function which search for given key in values. | |
This is very generic in the sense values and key can be of different type. | |
If they are of different type then caller must specify comp function to | |
perform comparision between key and values's item. | |
:param values: List of items in which key has to be search | |
:param key: search key | |
:param lo: start index to begin search | |
:param hi: end index where search will be performed | |
:param length: length of values | |
:param comp: a comparator function which can be used to compare key and values | |
:return: -1 if key is not found else index | |
""" | |
assert type(values[0]) == type(key) or comp, "can't be compared" | |
assert not (hi and length), "hi, length both can't be specified at the same time" | |
lo = lo | |
if not lo: | |
lo = 0 | |
if hi: | |
hi = hi | |
elif length: | |
hi = length - 1 | |
else: | |
hi = len(values) - 1 | |
while lo <= hi: | |
mid = lo + (hi - lo) // 2 | |
if not comp: | |
if values[mid] == key: | |
return mid | |
if values[mid] < key: | |
lo = mid + 1 | |
else: | |
hi = mid - 1 | |
else: | |
val = comp(values[mid], key) | |
# 0 -> a == b | |
# > 0 -> a > b | |
# < 0 -> a < b | |
if val == 0: | |
return mid | |
if val < 0: | |
lo = mid + 1 | |
else: | |
hi = mid - 1 | |
return -1 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment