Aryan PrajapatKnowledge Contributor
Implement Binary Search in Java using recursion.
Implement Binary Search in Java using recursion.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Questions | Answers | Discussions | Knowledge sharing | Communities & more.
// Java Program to Illustrate Recursive Binary Search
// Importing required classes
import java.util.*;
// Main class
class GFG {
// Method 1
// Recursive binary search
// Returns index of x if it is present
// in arr[l..r], else return -1
int binarySearch(int arr[], int l, int r, int x)
{
// Restrict the boundary of right index
// and the left index to prevent
// overflow of indices
if (r >= l && l x)
return binarySearch(arr, l, mid – 1, x);
// Else the element can only be present
// in right subarray
return binarySearch(arr, mid + 1, r, x);
}
// We reach here when element is not present in
// array
return -1;
}
// Method 2
// Main driver method
public static void main(String args[])
{
// Creating object of above class
GFG ob = new GFG();
// Custom input array
int arr[] = { 2, 3, 4, 10, 40 };
// Length of array
int n = arr.length;
// Custom element to be checked
// whether present or not
int x = 10;
// Calling above method
int result = ob.binarySearch(arr, 0, n – 1, x);
// Element present
if (result == -1)
// Print statement
System.out.println(“Element not present”);
// Element not present
else
// Print statement
System.out.println(“Element found at index ”
+ result);
}
}