Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def bin_search(a, x):
- n = len(a)
- def get(i):
- if i == 0:
- return float('-inf')
- elif i == n + 1:
- return float('inf')
- else:
- return a[i - 1]
- l, r = 0, len(a) + 1
- while l < r - 1:
- m = l + (r - l) / 2
- if get(m) <= x:
- l = m
- else:
- r = m
- if get(l) == x:
- return l - 1
- else:
- return -1
- assert bin_search([1, 2, 3], 3) == 2
- assert bin_search([], 3) == -1
- assert bin_search([1, 3], 2) == -1
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement