Site icon

Find element in an array using binary search algorithm in java (recursive)

Algorithm – find element in an array using binary search algorithm

Given an sorted array as shown in Fig 1, we would like to find element 70 in an array.  The algorithm is as follows:

Step 1: find element 70 in an input array using binary search algorithm

Fig 1: Search 70 in array [array indexes are low = 0, mid = 5, high = 9]

Step 2: find element 70 in an array using binary search algorithm.

Fig 2: Search 70 in array [array indexes are low = 5, mid = 7, high = 9]

Step 3: find element using binary search algorithm in java.

Fig 3: Search 70 in array [low = 5, mid = 5, high = 6]

Step 4: find element using binary search algorithm in java.

Fig 4: Search 70 in array [low =6, mid = 6, high = 6]

Program: find element in an array using binary search recursive algorithm

package org.learn.arrays;

public class BinarySearchRecursive {
	public static void main(String[] args) {
		int arr[] = {10,20,30,40,50,60,70,80,90,100};
		//low index
		int low = 0;
		//high index
		int high = arr.length - 1;
		int search = 70;
		int result = binarySearch(arr, search, low, high);
		if(result == -1) {
			System.out.printf("Element %d not found in array",search);			
		} else {
			System.out.printf("Element %d found at index : %d ",search,result);
		}
		System.out.println("");
		
		search = 60;
		result = binarySearch(arr, search, low, high);
		if(result == -1) {
			System.out.printf("Element %d not found in array",search);			
		} else {
			System.out.printf("Element %d found at index : %d",search,result);
		}
		System.out.println("");
		
		search = 110;
		result = binarySearch(arr, search, low, high);
		if(result == -1) {
			System.out.printf("Element %d not found in array",search);			
		} else {
			System.out.printf("Element %d found at index : %d",search,result);
		}
		System.out.println("");
	}

	private static int binarySearch(int[] arr, int value, int low, int high) {
		if (high < low)
			return -1;
		
		int middle = low + (high - low) / 2;
		if (value < arr[middle]) { // search between low ---> middle - 1
			return binarySearch(arr, value, low, middle - 1);
		} else if (value > arr[middle]) {
			//search in upper half middle + 1 -----> high
			//low to middle already covered in first case
			// so start search from middle + 1 to high here...
			return binarySearch(arr, value, middle + 1, high);
		} else {
			// value == arr[middle]
			//yes we got the element in binary search tree
			return middle;
		}	
	}
}

Output – element in an array in java (binary search recursive algorithm)

Element 70 found at index : 6
Element 60 found at index : 5
Element 110 not found in array
Exit mobile version