You will be given some numbers. Then there will contain some queries. In every query there will be given a range and a number. You have to say that, the given number exists in the range of values or not.
This is a companion discussion topic for the original entry at https://toph.co/p/exist-or-not-exist
#include <stdio.h>
#include <stdlib.h>
int *ara;
int binary_search(int l, int h, int x)
{
if(l > h) return -1;
int mid = (l+h)/2;
if(x == ara[mid]) return 1;
if(x > ara[mid]) return binary_search(mid+1, h, x);
else return binary_search(l, mid-1, x);
}
int main()
{
int n, q, l, r, s;
scanf("%d %d", &n, &q);
ara = (int *) malloc(sizeof(int)*(n+1));
for(int i = 1; i <= n; i++) scanf("%d", &ara[i]);
for(int j = 1; j <= q; j++) {
scanf("%d %d %d", &l, &r, &s);
if(binary_search(l, r, s) == 1) printf("YES\n");
else printf("NO\n");
}
return 0;
}
My code is getting wrong answer in test case 2. Can anyone help me?
The numbers are not sorted…binary search only operated on sorted dataset