0

I wrote this code, but it gives arrayoutofboundexception at the last index, but it is working for other indexes. please help :) In main, im passing the value of i = 0;

public int recursiveSearch(int key, int i)
    {
       int left = ((2*i) + 1);
       int right = ((2*i) + 2);
       if(isEmpty())
       {
           return -1;
       }  
       if(a[i] == key)
       {
           return i; 
       }
       else if(key < a[i])
       {
           int found = recursiveSearch(key, left);
           if(found == -1)
           {
               return recursiveSearch(key, right);
           }
           return found;
       }
       else
       {
           return -1;
       }
       
    }
  • Please provide stack trace. – papaya Oct 21 '20 at 05:12
  • You need to revise your algorithm. Consider this scenario. `a = [1, 2, 3]`, `key = 3`, `i = 0`. On the (first) call to `recursiveSearch`, it returns -1 even though the correct return value should be 2. – yoninja Oct 21 '20 at 06:17
  • At no point in your code do you even check the size of the array. And it is not a parameter passed through the stack. So how do you expect your code to terminate, other than through an array out of bounds? You need to take into account what happens, when you reach the 'end' of the array, and how to handle it. – TreffnonX Oct 21 '20 at 07:19

0 Answers0