Advertisement
Guest User

Untitled

a guest
Aug 19th, 2019
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.70 KB | None | 0 0
  1. #sorted = [2,4,5,8,9,12,18,22,25,30,40]
  2. sorted = [2,4,4,4,4,4,9,9,12,18,22,22,22,22,25,30,40]
  3. def binary_search(value,sorted):
  4.         left = 0
  5.         right = len(sorted)-1
  6.         while left <= right:
  7.             mid = int((left+right)/2) # get the index of mid value in the list
  8.             print ('mid is ', mid)
  9.             if sorted[mid]> value:
  10.                 right = mid -1
  11.             elif sorted[mid]< value:
  12.                 left = mid+1
  13.             else: # return the position of the first instance of the value
  14.                 pos = mid
  15.                 while sorted[pos-1]== value:
  16.                     pos= pos -1
  17.                 return pos
  18.        # from heir is the code to return closest value in the absence of any match
  19.         lower = value - sorted[mid-1]# find difference with value at lower index
  20.         upper = sorted[mid +1]-value # find difference with value at upper index
  21.         middiff= abs(value-sorted[mid])# find difference with value at mid index
  22.         while mid != len(sorted)-1:# runs as long as the mid value is not the last value in the list
  23.             if middiff < upper and middiff< lower:
  24.                 return mid
  25.             elif lower< upper:
  26.                 return mid-1
  27.             elif lower> upper :
  28.                 return mid +1
  29.             else:# if lower and upper are equal, return value at lower index
  30.                 return mid-1
  31.         if middiff < lower: # if the value is the last value in the list, we calculate only difference with value at  lower index
  32.             return mid
  33.         else:
  34.             return mid-1#if equal return value at lower index
  35.        
  36. print(sorted)        
  37. x = binary_search(27.5,sorted)
  38. print(x)
  39. print(sorted[x])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement