Liner List Manipulation

Question

Write a method in python to search for a value in a given list (assuming that the elements in the list are in ascending order) with the help of Binary Search method. The method should return –1 if the value does not present else it should return the position of the value present in the list.

Answer

def bSearch(L, key):
	low = 0
	high = len(L)-1
	found = False
	while (low <= high) and (not found):
		mid = (low+high)//2
		if L[mid] == key:
			found = True
		elif L[mid] < key:
			low = mid + 1
		else:
			high = mid - 1
		if found:
			return mid+1 # may even be 'return mid'
		else:
			return -1

Sponsor Area