### The recursive binary search algorithm

• The search problem

• Problem description:

• You are given a sorted array (of numbers) Example:

Problem:

• Locate the array element that has the value x

 Return the index of the array element that contains the value x Or: return −1 to indicate that the value x is not in the array.

• Example 1:

• Locate the array element that has the value 27

Solution:

• Example 2:

• Locate the array element that has the value 28

Solution:

• The recursive binary search algorithm

• The binary search algorithm (general case):

• Find x in array elements A[low .. high]:

• Compare x with the middle element in the array.

There are 3 possible outcomes:

• If x == A[middle] (value of the middle element of array):

 return middle (= the index of the middle element)

• If x < A[middle]:

• Find x in array elements A[low .. (middle−1)]

Note:

 This is a smaller problem of the same kind !

• If x > A[middle]:

• Find x in array elements A[(middle+1) .. high]

Note:

 This is a smaller problem of the same kind !

• Base case:

• Find x in an empty array A[low .. high] where low > high

Example:

• The recursive binary search algorithm in Java

• Java program:

 ``` public static int BinSearch( int x, int[] A, int low, int high ) { int middle; int mySol; if ( low > high ) { /* ------------------------------------------------------ Solve the base case: ------------------------------------------------------ */ return( -1 ); // Not found } else { /* ------------------------------------------------ Solve a non-trivial binary search ------------------------------------------------ */ middle = (low + high)/2; if ( x == A[middle] ) { mySol = middle; // Found x, return location in array } else if ( x < A[middle] ) { mySol = BinSearch( x, A, low, middle−1 ); // Solve smaller problem } else // x > A[middle] { mySol = BinSearch( x, A, middle+1, high ); // Solve smaller problem } return ( mySol ); } } ```

• Example Program: (Demo above code)

How to run the program:

 Right click on link and save in a scratch directory To compile:   javac Recurse4.java To run:          java Recurse4