Using Java Given the following method header give the code f

Using Java

Given the following method header, give the code for the function using a binary search of an array. Don\'t worry about the precondition (assume this is already true). public static boolean has 10 (intf] data, int start, int end)//Precondition: The elements data[start]...data[end] are sorted from smallest to largest. This//array segment might be empty (indicated by end being less than start).//Postcondition: A true return value indicates that the number 10 appears in the array//data[start]...data[end]. A false return value indicates that 10 doesn\'t appear.

Solution

public class BinarySearchRecursion {
   /**
   * @param args
   */
   public static void main(String[] args) {
       int arr[] = { 1, 3, 5, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 };
       boolean found = has10(arr, 0, arr.length - 1);

       if (found) {
           System.out.println(\"10 found \");
       } else {
           System.out.println(\"10 not found\");
       }
   }

   /**
   * @param arr
   * @param start
   * @param end
   * @return
   */
   public static boolean has10(int[] data, int start, int end) {
       int mid;
       int key = 10;
       if (end < start) {
           return false;
       }

       if (data.length <= 0) {
           return false;
       }
       mid = (start + end) / 2;

       if (data[mid] < key)
           return has10(data, mid + 1, end);
       else if (data[mid] > key)
           return has10(data, start, mid - 1);
       else
           return true;
   }
}

OUTPUT:

10 found

Using Java Given the following method header, give the code for the function using a binary search of an array. Don\'t worry about the precondition (assume this

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site