-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathBinary_Search_26.cpp
More file actions
52 lines (40 loc) · 806 Bytes
/
Binary_Search_26.cpp
File metadata and controls
52 lines (40 loc) · 806 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
#include <bits/stdc++.h>
using namespace std;
int binarySearch(int arr[], int val, int start, int end)
{
while (start <= end)
{
int mid = start + ((end - start) / 2);
if (arr[mid] == val)
return mid + 1;
else if (arr[mid] < val)
start = mid + 1;
else
end = mid - 1;
}
return -1;
}
int main()
{
int n;
cin >> n;
int arr[n];
for (int i = 0; i < n; i++)
{
cin >> arr[i];
if (i != 0 && arr[i] <= arr[i - 1])
{
cout << "Numbers are not in ascending order\n";
exit(0);
}
}
int m;
cin >> m;
while (m--)
{
int num;
cin >> num;
cout << binarySearch(arr, num, 0, n - 1) << " ";
}
return 0;
}