Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <cstring>
- #include <vector>
- #include <set>
- #include <map>
- #include <sstream>
- #include <cstdio>
- #include <algorithm>
- #include <stack>
- #include <queue>
- #include <cmath>
- #include <iomanip>
- #include <fstream>
- //#include <bits/stdc++.h>
- using namespace std;
- typedef long long ll;
- const ll INF = (1 << 30);
- const ll inf = (1LL << 60LL);
- const int maxn = 1e5 + 5;
- int main(int argc, const char * argv[]) {
- ios_base::sync_with_stdio(false);
- // given an array of n elements, check if the number x exists in this array
- // O(log2(n)) time
- int n, x;
- cin >> n >> x;
- vector<int> v(n);
- for(int i = 0; i < n; ++i) {
- cin >> v[i];
- }
- sort(v.begin(), v.end());
- int left_bound = 0;
- int right_bound = n - 1;
- while(left_bound <= right_bound) {
- int middle = (left_bound + right_bound) / 2; // middle of boundaries
- if(v[middle] > x) {
- right_bound = middle - 1;
- }
- else if(v[middle] < x) {
- left_bound = middle + 1;
- }
- else if(v[middle] == x) {
- cout << x << " exists in this array\n";
- break;
- }
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment