Abstract

Algorithm

# a = input, x = target value
def binary_search(a, x):
	# set start and end to initial scope of search
	start = 0
	end = len(a) - 1
	# searching loop
	while start <= end:
		mid = (start + end) // 2   # half point
		if x == a[mid]:            # found!
			return mid
		elif x > a[mid]:           # if target is larger, shrink scope to the right
			start = mid + 1
		else                       # if target is smaller, shrink scope to the right
			end = mid - 1
	return -1
# recursive algorithm
def binary_search(arr, start, end, target):
	# calculate mid index and store value
	mid = (start + end) // 2
	mid_value = arr[mid]

	if target == mid_value:   # found!!
		return mid
	elif mid_value > target:  # target value smaller than mid, adjust scope and call
		end = mid - 1
		binary_search(arr, start, end, target)
	elif mid_value < target:  # target value larger than mid value, adjust scope and call
		start = mid + 1
		binary_search(arr, start, end, target)
	else:
		return -1

Problems