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
def binary_search ( arr , l , r , x ) : NEW_LINE INDENT if r >= l : NEW_LINE INDENT mid = l + ( r - l ) / 2 NEW_LINE if arr [ mid ] == x : NEW_LINE INDENT return mid NEW_LINE DEDENT if arr [ mid ] > x : NEW_LINE INDENT return binary_search ( arr , l , mid - 1 , x ) NEW_LINE DEDENT return binary_search ( arr , mid + 1 , r , x ) NEW_LINE DEDENT return - 1 NEW_LINE DEDENT def findPos ( a , key ) : NEW_LINE INDENT l , h , val = 0 , 1 , arr [ 0 ] NEW_LINE while val < key : NEW_LINE INDENT l = h NEW_LINE h = 2 * h NEW_LINE val = arr [ h ] NEW_LINE DEDENT return binary_search ( a , l , h , key ) NEW_LINE DEDENT arr = [ 3 , 5 , 7 , 9 , 10 , 90 , 100 , 130 , 140 , 160 , 170 ] NEW_LINE ans = findPos ( arr , 10 ) NEW_LINE if ans == - 1 : NEW_LINE INDENT print " Element ▁ not ▁ found " NEW_LINE DEDENT else : NEW_LINE INDENT print " Element ▁ found ▁ at ▁ index " , ans NEW_LINE DEDENT