Question

int BinarySearch(int A[], int p, int r, int value)
{
    int q = (p + r) / 2;

    if (A[q] == value)
    {
        return q;   //value found
    }
    if (p == q) 
    {
        return 0;   //not found
    }
    if (A[q] > value)
    {
        return BinarySearch(A, p, q, value);
    }
    else
    {
        return BinarySearch(A, q + 1, r, value); 
    }
} //binary search ends here

Now, the problem is that whenever I want to search the last element of an array, this code gives an error. can anyone please explain why?

Was it helpful?

Solution

Make the search end case based on first index p and last index r,

int BinarySearch(int A[], int p, int r, int value)
{
    int q = (p + r) / 2;
    if( p > r )
    {
      return 0;
    }
    if (A[q] == value)
    {
        return q;   //value found
    }
    if (A[q] > value)
    {
        return BinarySearch(A, p, q-1, value);
    }
    else
    {
        return BinarySearch(A, q + 1, r, value); 
    }
} 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top