0

Did I code this problem correctly? here is my outcome output

In the searchRecursive method. in the searchRecusrsive method I am trying to check the element in the middle position , if the target is greater than the element in the middle position,recursively search for the second half of the array. if the target is less than the element in the middle position, recursively search the first half.

The first base case returns false if the low index exceeds the high index. the second base case returns true if the target is in the middle position.

class SearchSortedArray
{
  public static void main(String[] args)
  {
    int[] sorted = {10, 20, 30, 40};

    System.out.println("***Iterative***");
    for (int i = 0; i < sorted.length; i++)
    {
      System.out.println(sorted[i] + " found? " +
                         searchIterative(sorted[i], sorted));
      System.out.println((sorted[i] + 1) + " found? " +
                         searchIterative(sorted[i] + 1, sorted));
    }

    System.out.println("***Recursive***");
    for (int i = 0; i < sorted.length; i++)
    {
      System.out.println(sorted[i] + " found? " +
                         searchRecursive(sorted[i], sorted, 0, sorted.length - 1));
      System.out.println((sorted[i] + 1) + " found? " +
                         searchRecursive(sorted[i] + 1, sorted, 0, sorted.length - 1));
    }
  }

  private static boolean searchIterative(int target, int[] a)
  {
    int low    = 0,
        high   = a.length - 1,
        middle;

    while (low <= high)
    {
      middle = (low + high) / 2;
      if (target == a[middle])
        return true;
      if (target > a[middle])
        low = middle + 1;
      else
        high = middle - 1;
    }
    return false;
  }

  private static boolean searchRecursive(int target, int[] a, int low, int high)
  {
      if (low > high) return false;

      int middle;       
      middle = (low + high) / 2;


      if (target == a[middle]) 
        return true;


      if (target <  a[middle])           
      {
        return searchRecursive(target, a, low, middle -1);    
      }


      if (target >  a[middle])  

      { 
        return searchRecursive(target, a, middle+1, high);    
      }

      return false;
  }
}
  • 1
    1. `return searchRecursive(target, a, middle -1, low);` - you need to switch low and middle-1. 2. `return middle;` middle is int but your function returns boolean ... – Fildor May 06 '16 at 13:54
  • 1
    "my attempt at it does not work" - You really really do not want to write this sentence on SO. If you catch yourself doing it - immediatly go on to write 1. What the expected result is, 2. Whether you had exceptions, if so add stacktraces, 3. what the actual result was. – Fildor May 06 '16 at 13:57

0 Answers0