Skip to content

Commit 54b0a5d

Browse files
committed
Linear Search Algorithm
1 parent dc11dbf commit 54b0a5d

File tree

1 file changed

+61
-0
lines changed
  • CompetitiveProgramming/HackerEarth/Algorithms/Searching

1 file changed

+61
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
# You have been given an array A consisting of N integers. All the elements in this array A are unique. You have to
2+
# answer some queries based on the elements of this array. Each query will consist of a single integer x. You need to
3+
# print the rank based position of this element in this array considering that the array is 1 indexed. The rank
4+
# based position of an element in an array is its position in the array when the array has been sorted in ascending order.
5+
#
6+
# Note: It is guaranteed that all the elements in this array are unique and for each x belonging to a query, value ′x′
7+
# shall exist in the array
8+
#
9+
# Input Format
10+
#
11+
# The first line consists of a single integer N denoting the size of array A. The next line contains N unique integers,
12+
# denoting the content of array A. The next line contains a single integer q denoting the number of queries. Each of
13+
# the next q lines contains a single integer x denoting the element whose rank based position needs to be printed.
14+
#
15+
# Output Format
16+
#
17+
# You need to print q integers denoting the answer to each query.
18+
#
19+
# Constraints
20+
#
21+
# 1≤N≤105
22+
# 1≤A[i]≤109
23+
# 1≤q≤105
24+
# 1≤x≤109
25+
#
26+
# SAMPLE INPUT
27+
# 5
28+
# 1 2 3 4 5
29+
# 5
30+
# 1
31+
# 2
32+
# 3
33+
# 4
34+
# 5
35+
#
36+
# SAMPLE OUTPUT
37+
# 1
38+
# 2
39+
# 3
40+
# 4
41+
# 5
42+
43+
n = int(input())
44+
array = [int(i) for i in input().split()]
45+
array.insert(0, 0)
46+
array.sort()
47+
q = int(input())
48+
49+
def binarySearch(low, high, element):
50+
while(low <= high):
51+
mid = (low + high) // 2
52+
if array[mid] == element:
53+
return mid
54+
elif array[mid] < element:
55+
low = mid + 1
56+
else:
57+
high = mid - 1
58+
59+
for i in range(q):
60+
number = int(input())
61+
print(binarySearch(0,len(array), number))

0 commit comments

Comments
 (0)