fork download
  1. import numpy as np
  2.  
  3. arr = np.array([0.23, 2.32, 4.04, 5.02, 6.84, 10.12, 10.34, 11.93,12.44])
  4.  
  5. def binary_search(arr, val):
  6. # val must be in the closed interval between arr[i-1] and arr[i],
  7. # unless one of i-1 or i is beyond the bounds of the array.
  8. i = np.searchsorted(arr, val)
  9.  
  10. if i == 0:
  11. # Smaller than the smallest element
  12. return i
  13. elif i == len(arr):
  14. # Bigger than the biggest element
  15. return i - 1
  16. elif val - arr[i - 1] <= arr[i] - val:
  17. # At least as close to arr[i - 1] as arr[i]
  18. return i - 1
  19. else:
  20. # Closer to arr[i] than arr[i - 1]
  21. return i
  22.  
  23. cases = [10, 12, 100, 10.12, 12.43, 0.5]
  24. print(*[binary_search(arr, c) for c in cases], sep=',')
  25. print(*[arr[binary_search(arr, c)] for c in cases], sep=',')
Success #stdin #stdout 0.14s 24716KB
stdin
Standard input is empty
stdout
5,7,8,5,8,0
10.12,11.93,12.44,10.12,12.44,0.23