0
#include <stdio.h>
#include <stdlib.h>

long int binary_search(long int *arr,long int n,long int key){
    //Implement binary search
    long int s = 0;
    long int e = n - 1;

    while(s<=e){
        long int mid = (s+e)/2;

        if(arr[mid] == key){
            return mid;
        }
        else if(arr[mid] > key){
            e = mid - 1;
        }
        else{
            s = mid + 1;
        }
    }
    return -1;
}

int main()
{
    long int n=0, q=0, i=0;
    long int temp=0;
    scanf("%ld", &n);
    scanf("%ld", &q);
    long int arr[100100];

    for(i=0; i<n; i++){
        scanf("%ld", &arr[i]);
    }

    for(i=0;i<q;i++){
        scanf("%ld", &temp);
        printf("%ld\n", binary_search(arr,n,temp));
    }

    return 0;
}

It's a simple code, and it's a question from an online judge. source : https://www.spoj.com/problems/BSEARCH1/

The code gets two values, one is the number of elements in the array, the other is the number of queries, and if the element is not there, I have to print -1. What I am getting is "wrong answer", and I know the problem is on the binary search implementation. I tried to debbug and tried many inputs but I cannot see a problem on it, I'd appreciate any hints, thanks in advance...

Drew Dormann
  • 59,987
  • 13
  • 123
  • 180

0 Answers0