Code
def binary_search_cycle(data_set, value):
start = 0
end = len(data_set) - 1
while True:
mid_idx = (start + end) / 2
if data_set[mid_idx] > value:
end = mid_idx
elif data_set[mid_idx] < value:
start = mid_idx
else:
return mid_idx
def binary_search_recursive(data_set, value, start=None, end=None):
if start is None and end is None:
start = 0
end = len(data_set) - 1
mid_idx = (end + start) / 2
if data_set[mid_idx] == value:
return mid_idx
elif data_set[mid_idx] > value:
result = binary_search_recursive(data_set, value, start, mid_idx)
else:
result = binary_search_recursive(data_set, value, mid_idx + 1, end)
return result
Test
def test():
l = list(range(1001))
print binary_search_recursive(l, 85)
print binary_search_cycle(l, 85)