VOOZH about

URL: https://www.geeksforgeeks.org/java/binary-search-in-java/

⇱ Binary Search in Java - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Binary Search in Java

Last Updated : 12 May, 2026

Binary Search is an efficient searching algorithm used to find an element in a sorted array by repeatedly dividing the search range into halves. In Java, it is commonly used to improve searching performance compared to linear search.

Example:

Input: arr = { 3, 5, 7, 8, 10, 12, 15}, target = 7
Output: 2

Input: arr = { 1, 2, 3, 4, 5, 6, 7, 8} target = 10
Output: -1 ( Because the target is not present in the array)

Binary Search Algorithm

Below is the Algorithm designed for Binary Search:

  • Take input array and target value.
  • Initialize start = 0 and end = array.length - 1.
  • Calculate mid = (start + end)/2.
  • If array[mid] == target, return mid.
  • If array[mid] < target, search the right subarray (start = mid + 1).
  • If array[mid] > target, search the left subarray (end = mid - 1).
  • Repeat steps 3–6 until start > end.
  • If element not found, return -1.

Note: If there are duplicates, there is no guarantee which one will be found.

Methods in Java to implement Binary Search in Java

It includes approaches like iterative and recursive methods to efficiently search an element in a sorted array.

1. Iterative Method for Binary Search  in Java


Output
Element to be searched is : 10
Element is present at index: 3

2. Recursive Method for Binary Search


Output
Element to be searched is : 10
Element is present at index: 3

3. In Build Methods

For Arrays:Arrays.binarySearch()  works for arrays which can be of primitive data type also.


Output
Element to be searched is : 22
22 found at index = 3
Element to be searched is : 40
40 Not found

For Collections: Binary search in Java Collections using Collections.binarySearch() returns the index if the element is found; otherwise, it returns -(insertion point) - 1, where the insertion point is the position to maintain sorted order.

Note: The list must be sorted before calling binary search to get correct results.


Output
Element to be searched is : 10
10 found at index = 3
15 Not found

Importance of Binary Search

  • It eliminates half the remaining elements in each step, making it optimal for large datasets.
  • It is used in databases, search algorithms, and performance critical applications.
Comment