Given a sorted array of size N and an integer K, find the position at which K is present in the array using binary search.
// { Driver Code Starts
// Initial template for C++
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
// User function template for C++
class Solution {
public:
long long int binarysearch(int arr[], int n, int k) {
long long int l = 0, r = n - 1, mid, ans;
while (l <= r)
{
mid = (r - l) / 2 + l;
if (arr[mid] == k)
{
ans = mid;
l = n;
}
else if (arr[mid] > k)
{
r--;
}
else
{
l++;
}
}
int ans2=-1;
if(ans == mid){
ans2 = ans;
}
return ans2;}
};
// { Driver Code Starts.
int main() {
int t;
cin >> t;
while (t--) {
int N;
cin >> N;
int arr[N];
for (int i = 0; i < N; i++) cin >> arr[i];
int key;
cin >> key;
Solution ob;
int found = ob.binarysearch(arr, N, key);
cout << found << endl;
}
}
// } Driver Code Ends