Guest User

Untitled

a guest
Feb 19th, 2018
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.82 KB | None | 0 0
  1. def binary_search(array, element_ts):
  2. is_sorted = lambda x: all([el>x[i-1] for i, el in enumerate(x[1:], 1)])
  3. if len(array) < 1000 and not is_sorted(array):
  4. array = sorted(array)
  5.  
  6. def recurse(first, last):
  7. mid = (first + last) // 2
  8. if array[mid] < element_ts:
  9. return recurse(mid+1, last)
  10. elif array[mid] > element_ts:
  11. return recurse(first, mid-1)
  12. elif array[mid] == element_ts:
  13. return mid + 1
  14. elif first > last:
  15. return -1
  16. else:
  17. raise
  18.  
  19. return recurse(0, len(array)-1)
  20.  
  21. if __name__ == '__main__':
  22. _ = input()
  23. array = list(map(int, input().split()))
  24. queries_num = int(input())
  25. for i in range(queries_num):
  26. query = int(input())
  27. print(binary_search(array, query))
Add Comment
Please, Sign In to add comment