The code for the binary search is below.
def binary_search(src, target_value):
result = False
lower_index = 0
higher_index = len(src)-1
while True:
dst = src[lower_index:higher_index+1]
medium_index = (lower_index + higher_index) // 2
if src[medium_index] == target_value:
result = True
break
if (higher_index - lower_index) == 1:
break
if target_value >= dst[medium_index]:
lower_index = medium_index
else:
higher_index = medium_index
return result
def main():
src = [1, 2, 3, 4, 5, 6] #Already sorted
target_value = 4
if binary_search(src, target_value):
print('Found!')
else:
print('Not Found')
if __name__ == '__main__':
main()
The execution result is as follows.
Found!
Thank you for reading until the end. Let's meet again.
Recommended Posts