I want to do a binary search in python:
def binarySearch(data, val):
Where data
is a sorted array and value
is the value being searched for. If the value is found, I want to return the index
(such that data[index] = val
). If the value is not found, I want to return the index
of the item that is closest to that value.
Here is what I've got:
def binarySearch(data, val):
high = len(data)-1
low = 0
while True:
index = (high + low) / 2
if data[index] == val:
return index
if data[index] < val:
low = index
if data[index] > val:
high = index
Something like this should work. It returns an array with two indexes. If val is found, both values in the return array are the same. Otherwise, it returns the indexes of the two items closest to val.
def binarySearch(data, val):
highIndex = len(data)-1
lowIndex = 0
while highIndex > lowIndex:
index = (highIndex + lowIndex) / 2
sub = data[index]
if data[lowIndex] == val:
return [lowIndex, lowIndex]
elif sub == val:
return [index, index]
elif data[highIndex] == val:
return [highIndex, highIndex]
elif sub > val:
if highIndex == index:
return sorted([highIndex, lowIndex])
highIndex = index
else:
if lowIndex == index:
return sorted([highIndex, lowIndex])
lowIndex = index
return sorted([highIndex, lowIndex])