Challenge: Binary Search
Completed
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
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
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module