java

Binary Search in Java: Recursive + Iterative

In this tutorial, we are going to see how to perform a binary search iteratively and recursively in Java.

Binary search is used to find an item based on multiple items. Binary search is faster than linear search.

In binary search, the array elements must be in ascending order. If you have an unsorted array, you can sort the array using the Arrays.sort(array) method.
 

 

 

Example 1: Iteratively
public class BinarySearch{
  /*
	arr[] : the array in which we will look for the value
	l : last item
	f : first item
	val : value to find
  */
  public static void binarySearch(int arr[], int f, int l, int val){
    int mid = (f + l)/2;
    while(f <= l){
      if (arr[mid] < val){
        f = mid + 1;   
      }else if(arr[mid] == val){
        System.out.println("The item is at index: " + mid);
        break;
      }else{
         l = mid - 1;
      }
      mid = (f + l)/2;
   }
    if (f > l){
      System.out.println("Item does not exist!");
    }
   }
 
  public static void main(String args[]){
		int arr[] = {1, 2, 3, 4, 5, 6, 7};
		int val = 4;
		int l = arr.length-1;
		binarySearch(arr,0,l,val);	
  }
}

Output:

The item is at index: 3

 

 

Example 2: Using recursion
public class BinarySearch{
  /*
	arr[] : the array in which we will look for the value
	l : last item
	f : first item
	val : value to find
  */
   public static int binarySearch(int arr[], int f, int l, int val){
		if (l >= f){
			int mid = f + (l - f)/2;
			if (arr[mid] == val){
				return mid;
			}
			if (arr[mid] > val){
				//search in the sub-array on the left
				return binarySearch(arr, f, mid-1, val); 
			}else{
				//search in the sub-array on the right 
				return binarySearch(arr, mid+1, l, val); 
			}
		}
		return -1;
   }
   public static void main(String args[]){
		int arr[] = {1, 2, 3, 4, 5, 6, 7};
		int val = 4;
		int l = arr.length-1;
		int res = binarySearch(arr,0,l,val);	
		if (res != -1)
			System.out.println("The item is at index: " + res);
		else
			System.out.println("Item does not exist!");
   }
}

Output:

The item is at index: 3
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *