human
Find position of an element in a sorted array of infinite numbers | Binary search algorithm implementation.
function takes an infinite size array and a key to be searched and returns its position if found else - 1. We don 't know size of a[] and we can assume size to be infinite in this function. NOTE THAT THIS FUNCTION ASSUMES a[] TO BE OF INFINITE SIZE THEREFORE, THERE IS NO INDEX OUT OF BOUND CHECKING.
Find h to do binary search.
store previous high.
double high index.
update new val.
at this point we have updated low and high indices , thus use binary search between them.
Driver function"
Solution in Python:
 What is a code to find position of an element in a sorted array of infinite numbers and the other steps required?
assistant
#Here is code to find position of an element in a sorted array of infinite numbers and the other steps required.
 def binary_search ( arr , l , r , x ) :
	if r >= l :
		mid = l + ( r - l ) / 2
		if arr [ mid ] == x :
			return mid
		if arr [ mid ] > x :
			return binary_search ( arr , l , mid - 1 , x )
		return binary_search ( arr , mid + 1 , r , x )
	return - 1
def findPos ( a , key ) :
	l , h , val = 0 , 1 , arr [ 0 ]
	while val < key :
		l = h
		h = 2 * h
		val = arr [ h ]
	return binary_search ( a , l , h , key )
arr = [ 3 , 5 , 7 , 9 , 10 , 90 , 100 , 130 , 140 , 160 , 170 ]
ans = findPos ( arr , 10 )
if ans == - 1 :
	print " Element ▁ not ▁ found "
else :
	print " Element ▁ found ▁ at ▁ index " , ans