forked from MAYANK25402/Hactober-2023-1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSearchingInSortedArray.cpp
62 lines (48 loc) · 1.1 KB
/
SearchingInSortedArray.cpp
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
//QUES. - Given an array arr[] sorted in ascending order of size N and an integer K. Check if K is present in the array or not.
//{ Driver Code Starts
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
class Solution{
public:
// Function to find element in sorted array
// arr: input array
// N: size of array
// K: element to be searche
int searchInSorted(int arr[], int N, int K)
{
// Your code here
int low=0,high=N-1;
while(low<=high){
int mid=(low+high)/2;
if(arr[mid] == K){
return 1;
}
else if(arr[mid] > K){
high=mid-1;
}
else{
low=mid+1;
}
}
return -1;
}
};
//{ Driver Code Starts.
int main(void)
{
int t;
cin >> t;
while(t--){
int n, k;
cin >> n >> k;
int arr[n];
for(int i = 0;i<n;i++){
cin >> arr[i];
}
Solution ob;
cout << ob.searchInSorted(arr, n, k) << endl;
}
return 0;
}
// } Driver Code Ends