-
Notifications
You must be signed in to change notification settings - Fork 0
/
Searching an element in a sorted array
72 lines (65 loc) · 1.41 KB
/
Searching an element in a sorted array
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
Given a sorted array arr[] of N integers and a number K is given. The task is to check if the element K is present in the array or not.
Input:
First line of input contains number of testcases T. For each testcase, first line of input contains number of elements in the array and the number K seperated by space. Next line contains N elements.
Output:
For each testcase, if the element is present in the array print "1" (without quotes), else print "-1" (without quotes).
Constraints:
1 <= T <= 100
1 <= N <= 106
1 <= K <= 106
1 <= arr[i] <= 106
Example:
Input:
2
5 6
1 2 3 4 6
5 2
1 3 4 5 6
Output:
1
-1
Explanation:
Testcase 1: Since, 6 is present in the array at index 4 (0-based indexing), so output is 1.
Testcase 2: Since, 2 is not present in the array, so output is -1.
#include<algorithm>
#include<cmath>
#include<bits/stdc++.h>
#include<stack>
using namespace std;
int _WhoWillWin(int arr[],int low,int high,int key)
{
if(low<=high)
{
int mid=low+(high-low)/2;
if(arr[mid]==key)
{
return 1;
}
else if(arr[mid]>key)
{
return _WhoWillWin(arr,low,mid-1,key);
}
else
{
return _WhoWillWin(arr,mid+1,high,key);
}
}
return -1;
}
int main()
{
int test;
std::cin>>test;
while(test--)
{
int n,key;
std::cin>>n>>key;
int arr[n];
for(int i=0;i<n;i++)
{
std::cin>>arr[i];
}
std::cout<<_WhoWillWin(arr,0,n-1,key)<<endl;
}
return 0;
}