You are given a sorted array of numbers, and followed by number of queries, for each query if the queried number is present in the array print its position, else print -1.
Input
First line contains N Q, number of elements in the array and number of queries to follow,
Second line contains N numbers, elements of the array, each number will be -10^9<= ai <= 10^9, 0 < N <= 10^5, 0 < Q <= 5*10^5
Output
For each element in the query, print the elements 0 based location of its first occurence, if present, otherwise print -1.
Example
Input: 5 4
2 4 7 7 9
7
10
4
2 Output: 2
-1
1
0
#include <iostream>
#include <cstdio>
#define MAX 100000
int a[MAX];
int N, Q;
using namespace std;
int bsearch (int x) {
int mid, le = 0;
int ri = N - 1;
while (le < ri) {
mid = le + ((ri - le) >> 1);
if (a[mid] >= x) {
ri = mid;
}
else {
le = mid +1;
}
}
if (a[le] == x) {
return le;
}
else {
return -1;
}
}
int main () {
int x;
scanf("%d%d", &N, &Q);
for (int i = 0; i < N; i++) {
scanf("%d",&a[i]);
}
while (Q--) {
scanf("%d", &x);
printf("%d\n",bsearch(x));
}
return 0;
}