Binary Search
Write a Python program for binary search.
In computer science, binary search, also known as half-interval search, is a search algorithm that finds the position of a target value within a sorted array. Binary search compares the target value to the middle element of the array. If they are not equal, the half in which the target cannot lie is eliminated and the search continues on the remaining half, again taking the middle element to compare to the target value, and repeating this until the target value is found. If the search ends with the remaining half being empty, the target is not in the array.
def binary_search(item_list, item):
first = 0
last = len(item_list)-1
found = False
while (first <= last and not found):
mid = (first+last)//2
if item_list[mid] == item:
found = True
else:
if item < item_list[mid]:
last = mid - 1
else:
first = mid + 1
return found
mylist = [2,3,1,12,34]
mylist
mylist.sort()
mylist
print(binary_search(mylist, 12))
print(binary_search(mylist, 13))
## Giving unsorted array
def binary (item_list, item):
item_list.sort()
print(item_list)
first = 0
last = len(item_list)-1
found = False
while (first <= last and not found):
mid = (first+last)//2
if item_list[mid] == item:
found = True
else:
if item < item_list[mid]:
last = mid - 1
else:
first = mid + 1
return found
mylist = [2,3,1,12,34]
print(binary(mylist, 12))
print(binary(mylist, 13))