Created
September 15, 2019 23:09
-
-
Save nathanesau/b52fa38dceb9239d8dc0bc10603124f0 to your computer and use it in GitHub Desktop.
Binary Search (Hackerearth)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <vector> | |
#include <algorithm> | |
#include <iostream> | |
// Write your code here | |
int binary_search(const std::vector<int> &a, int e) | |
{ | |
int l = 0; | |
int r = a.size() - 1; | |
while (l <= r) { | |
int m = l + (r - l) / 2; | |
if (a[m] == e) | |
return m + 1; | |
if (a[m] < e) | |
l = m + 1; | |
else | |
r = m - 1; | |
} | |
return -1; | |
} | |
// output to a | |
void read_array(int n, std::vector<int> &a) | |
{ | |
int e; | |
int count = 0; | |
while(count < n) { | |
std::cin >> e; | |
a.push_back(e); | |
count += 1; | |
} | |
} | |
int main() | |
{ | |
int n; | |
int q; | |
std::cin >> n; | |
std::vector<int> a; | |
read_array(n, a); | |
std::cin >> q; | |
std::vector<int> queries; | |
read_array(q, queries); | |
std::sort(a.begin(), a.end()); | |
for(auto e : queries) { | |
std::cout << binary_search(a, e) << std::endl; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment