Guest User

Untitled

a guest
Jan 19th, 2018
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.73 KB | None | 0 0
  1. # Recursive binary search
  2.  
  3. def binarySearch (arr, l, r, x):
  4.  
  5. # Check base case
  6. if r >= l:
  7.  
  8. mid = l + (r - l)/2
  9.  
  10. # If element is present at the middle itself
  11. if arr[mid] == x:
  12. return mid
  13.  
  14. # If element is smaller than mid, then it
  15. # can only be present in left subarray
  16. elif arr[mid] > x:
  17. return binarySearch(arr, l, mid-1, x)
  18.  
  19. # Else the element can only be present
  20. # in right subarray
  21. else:
  22. return binarySearch(arr, mid+1, r, x)
  23.  
  24. else:
  25. # Element is not present in the array
  26. return -1
  27.  
  28. # Test array
  29. arr = [10, 20, 30, 40, 50, 60, 70, 80, 90]
  30. x = 40
  31.  
  32. # Function call
  33. result = binarySearch(arr, 0, len(arr)-1, x)
Add Comment
Please, Sign In to add comment