Tag: otherwise return = = Bin Arch BSP Middle find back
Assume that there are n≥1 different integers that have been stored in the order from small to large in the array element a[0], ..., a[n-1]. What we need to do is to determine if the integer x is stored in an array element and, if so, X=a[j], then return J (subscript of the element being found); otherwise 1.
1 defBinarySearch (a,x):2n =Len (A)3Left, right = 0, n-14 whileLeft <=Right :5Middle = (left+right+1)/26 ifx = =A[middle]:7 returnMiddle8 elifX >A[middle]:9left = middle + 1Ten Else: Oneright = Middle-1 A return-1#Not found
Recursive algorithm:
1 #-*-coding:cp936-*-2 #returns the index of x in a3 defBinarySearch (a,x,l,r):4n =Len (A)5 #L,r are the boundaries to find, preferably 0,n-16Left, right =L, R7 whileLeft <=Right :8Middle = (left + right + 1)/29 ifx = = A[middle]:returnMiddleTen elifX >A[middle]: One returnBinarySearch (A, X, middle + 1, right) A Else: - returnBinarySearch (A, X, left, middle-1)
Two-point search-python