Skip to content

Instantly share code, notes, and snippets.

@Ch-sriram
Last active June 9, 2020 10:25
Show Gist options
  • Save Ch-sriram/3421b62411f95755276565c010a7f713 to your computer and use it in GitHub Desktop.
Save Ch-sriram/3421b62411f95755276565c010a7f713 to your computer and use it in GitHub Desktop.
Searching an element in a sorted array - Recursive Binary Search [O(N + log(N))].
// Problem link: https://practice.geeksforgeeks.org/problems/who-will-win/0/
#include <vector>
#include <iostream>
using namespace std;
#define ull uint64_t
bool binary_search(const vector<int> &ar, const int key, int lo, int hi) {
// base case
if(lo > hi) return false;
int mid = lo + ((hi-lo)/2);
if(ar[mid] == key) return true;
else if(ar[mid] > key) return binary_search(ar, key, lo, mid-1);
else return binary_search(ar, key, mid+1, hi);
}
int main() {
int t; cin >> t;
while(t--) {
int n, key; cin >> n >> key;
vector<int> ar(n);
for(int i = 0; i < n; ++i)
cin >> ar[i];
bool found = binary_search(ar, key, 0, ar.size()-1);
string ans = found == false ? "-1" : "1";
cout << ans << endl;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment