Challenge: Binary Search

Lab C++ Beginner 10 points

Read a sorted list of distinct numbers and q queries. For each query print its index, or -1. Write the binary search yourself.

Input

Line 1: n. Line 2: n sorted numbers. Line 3: q. Line 4: q numbers.

Output

One index per query.

Example

Input

6
3 8 15 21 34 42
4
42 3 5 34

Output

5
0
-1
4
Sample input available Sample output available
Editor
C++

Hints

Keep lo and hi; mid = lo + (hi - lo) / 2.

Move lo up or hi down depending on v[mid].

Solution explanation

O(log n) per query.

Show solution
#include <iostream>
#include <vector>
using namespace std;

int main() {
    int n;
    cin >> n;
    vector<int> v(n);
    for (int& x : v) cin >> x;
    int q;
    cin >> q;
    while (q--) {
        int t;
        cin >> t;
        int lo = 0, hi = n - 1, ans = -1;
        while (lo <= hi) {
            int mid = lo + (hi - lo) / 2;
            if (v[mid] == t) { ans = mid; break; }
            if (v[mid] < t) lo = mid + 1;
            else hi = mid - 1;
        }
        cout << ans << endl;
    }
    return 0;
}
Output
Answer
HOME LABS COMMUNITY DASHBOARD