Skip to content

Commit 6175ed0

Browse files
committed
Binary Search Algorithm
1 parent 54b0a5d commit 6175ed0

File tree

1 file changed

+78
-0
lines changed

1 file changed

+78
-0
lines changed
Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
# You are given an array A of size N, and Q queries to deal with. For each query, you are given an integer X, and
2+
# you're supposed to find out if X is present in the array A or not.
3+
#
4+
# Input:
5+
# The first line contains two integers, N and Q, denoting the size of array A and number of queries. The second line
6+
# contains N space separated integers, denoting the array of elements Ai. The next Q lines contain a single integer X
7+
# per line.
8+
#
9+
# Output:
10+
# For each query, print YES if the X is in the array, otherwise print NO.
11+
#
12+
# Constraints:
13+
# 1 <= N, Q <= 105
14+
# 1 <= Ai <= 109
15+
# 1 <= X <= 109
16+
#
17+
# SAMPLE INPUT
18+
# 5 10
19+
# 50 40 30 20 10
20+
# 10
21+
# 20
22+
# 30
23+
# 40
24+
# 50
25+
# 60
26+
# 70
27+
# 80
28+
# 90
29+
# 100
30+
#
31+
# SAMPLE OUTPUT
32+
# YES
33+
# YES
34+
# YES
35+
# YES
36+
# YES
37+
# NO
38+
# NO
39+
# NO
40+
# NO
41+
# NO
42+
43+
# Using binary search (non-efficient)
44+
n, q = map(int, input().split())
45+
array = [int(i) for i in input().split()]
46+
array.insert(0, 0)
47+
array.sort()
48+
49+
def binarySearch(low, high, element):
50+
while(low <= high):
51+
mid = (low + high) // 2
52+
try:
53+
if array[mid] == element:
54+
return mid
55+
elif array[mid] < element:
56+
low = mid + 1
57+
else:
58+
high = mid - 1
59+
except IndexError:
60+
return False
61+
62+
for i in range(q):
63+
number = int(input())
64+
ans = binarySearch(0,len(array), number)
65+
if ans:
66+
print('YES')
67+
else:
68+
print('NO')
69+
70+
# using traditional python (set as they are hashtables, hence efficient)
71+
in_ = input().split()
72+
arr = [x for x in input().split()]
73+
arr =set(arr) # since python set is a hashtable and O(n) in hashtbale is O(1)
74+
for i in range(int(in_[1])):
75+
if input() in arr:
76+
print("YES")
77+
else:
78+
print("NO")

0 commit comments

Comments
 (0)