-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathCode Binary Search.py
45 lines (33 loc) · 1.02 KB
/
Code Binary Search.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# You have been given a sorted(in ascending order) integer array/list(ARR) of size N and an element X.
# Write a function to search this element in the given input array/list using 'Binary Search'.
# Return the index of the element in the input array/list.
# In case the element is not present in the array/list, then return -1.
from sys import stdin
def binarySearch(arr, n, x):
#Your code goes here
start = 0
end = n - 1
mid = start
while start <= end:
mid = start + (end - start) // 2
if arr[mid] > x:
end = mid - 1
elif arr[mid] < x:
start = mid + 1
else:
return mid
return -1
#Taking Input Using Fast I/O
def takeInput():
n = int(stdin.readline().strip())
if n == 0:
return list(), 0
arr = list(map(int, stdin.readline().strip().split(" ")))
return arr, n
#main
arr, n = takeInput()
t = int(stdin.readline().strip())
while t > 0:
x = int(input().strip())
print(binarySearch(arr, n, x))
t -= 1