Program: Algorithms_4_binarysearch.py
#Algorithms and Computational Thinking
#Program for Example 4
#
#binary search (non-recursive version)
def searchTarget(target, target_list):
start = 0
end = len(target_list) - 1
position = -1
while start <= end:
checkpoint = (start+end )// 2
if target_list[checkpoint] == target:
position = checkpoint
break
elif target_list[checkpoint] < target:
start = checkpoint + 1
else:
end = checkpoint - 1
return position
target_item = 150
MyList = [12, 15, 44, 47, 88, 90, 92, 140, 150, 200, 300, 303, 550, 966, 980]
target_position = searchTarget(target_item, MyList)
if (target_position == -1):
print "Element was not found"
else:
print "Element was found at position: ", target_position
Output
Element was found at position: 8
