-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary_search.cpp
More file actions
53 lines (45 loc) · 805 Bytes
/
Copy pathbinary_search.cpp
File metadata and controls
53 lines (45 loc) · 805 Bytes
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
46
47
48
49
50
51
52
53
#include <iostream>
using namespace std;
int binarySearch(int *input, int n, int val)
{
// Write your code here
int start = 0, end = n - 1;
int mid;
while (start <= end)
{
mid = (start + end) / 2;
if (input[mid] == val)
{
return mid;
}
else if (val < input[mid])
{
end = mid - 1;
}
else
{
start = mid + 1;
}
}
return -1;
}
int main()
{
int size;
cin >> size;
int *input = new int[size];
for (int i = 0; i < size; ++i)
{
cin >> input[i];
}
int t;
cin >> t;
while (t--)
{
int val;
cin >> val;
cout << binarySearch(input, size, val) << endl;
}
delete[] input;
return 0;
}