Java question Suppose an array contains the integers 1 to 10
Java question:
Suppose an array contains the integers 1 to 10 in ascending order. How many probes will a binary search perform to find 3 in the array.
Solution
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
 package chegg;
 public class Program {
  
 public static int binarySearch(int[] arr,int low,int high,int key)
 {
 System.out.println(\"Calling binary search for low \"+low + \" and high \"+high );
 if(low>high)
 return -1;
   
 int mid = (low+high)/2;
   
 if(arr[mid]==key)
 return mid;
 else if(arr[mid]>key)
 return binarySearch(arr,0,mid-1,key);
 else
 return binarySearch(arr,mid+1,high,key);
 }
public static void main(String[] args)
 {
 int[] arr = {1,2,3,4,5,6,7,8,9,10};
 int index = binarySearch(arr,0,9,3);
 System.out.println(\"Index is : \"+index);
 }
 }
Output:
Calling binary search for low 0 and high 9
 Calling binary search for low 0 and high 3
 Calling binary search for low 2 and high 3
 Index is : 2
So total 3 probes will be done

