summaryrefslogtreecommitdiffstats
path: root/01-algorithmic_toolbox/03-divide_and_conquer/01-binary_search/binary_search.cpp
blob: 40f8f01778bba047db201d9dd00803129169ac95 (plain)
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
#include <iostream>
#include <cassert>
#include <vector>

using std::vector;

int binary_search(const vector<int> &a, int x)
{
  int left = 0, right = (int) a.size();
  while (left <= right) {
      int mid = (left + right) / 2;
      if (a[mid] == x) return mid;
      if (a[mid] < x) left = (mid + 1);
      else right = (mid - 1);
  }
  return -1;
}

int linear_search(const vector<int> &a, int x) {
  for (size_t i = 0; i < a.size(); ++i) {
    if (a[i] == x) return i;
  }
  return -1;
}

int main() {
  int n;
  std::cin >> n;
  vector<int> a(n);
  for (size_t i = 0; i < a.size(); i++) {
    std::cin >> a[i];
  }
  int m;
  std::cin >> m;
  vector<int> b(m);
  for (int i = 0; i < m; ++i) {
    std::cin >> b[i];
  }
  for (int i = 0; i < m; ++i) {
    std::cout << binary_search(a, b[i]) << ' ';
  }
  std::cout << '\n';
}