fork download
  1. from math import floor
  2.  
  3. def binary_search(Array, Search_Term):
  4. n = len(Array)
  5. L = 0
  6. R = n-1
  7.  
  8. while L <= R:
  9. mid = floor((L+R)/2)
  10. # print values of L,R and mid
  11. print(L,mid,R)
  12. if Array[mid] < Search_Term:
  13. L = mid + 1
  14. elif Array[mid] > Search_Term:
  15. R = mid - 1
  16. else:
  17. return mid
  18. return -1
  19.  
  20.  
  21. # Insert your array here
  22. A = [ 1, 2, 3, 4, 7, 14, 14, 15, 18]
  23. # term to be searched
  24. term = 14
  25. index = binary_search(A, term)
  26. if index >= 0:
  27. print("{} is at index {}".format(A[index], index))
  28. else:
  29. print("Search term not found")
Success #stdin #stdout 0.03s 9060KB
stdin
Standard input is empty
stdout
0 4 8
5 6 8
14 is at index 6