![]() |
VOOZH | about |
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: 2Input: arr = { 1, 2, 3, 4, 5, 6, 7, 8} target = 10
Output: -1 ( Because the target is not present in the array)
Below is the Algorithm designed for Binary Search:
Note: If there are duplicates, there is no guarantee which one will be found.
It includes approaches like iterative and recursive methods to efficiently search an element in a sorted array.
Element to be searched is : 10 Element is present at index: 3
Element to be searched is : 10 Element is present at index: 3
For Arrays:Arrays.binarySearch() works for arrays which can be of primitive data type also.
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.
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.