How to implement a binary search in Java? What are its types?
Java’s Arrays class offers the ‘binarySearch ()’ method, which executes a binary search on the specified Array. Binary Search Example in Java using Arrays.binarySearch()
- import java.util.Arrays;
- class BinarySearchExample2{
- public static void main(String args[]){
- int arr[] = {10,20,30,40,50};
- int key = 30;
- int result = Arrays.binarySearch(arr,key);
- if (result < 0)
- System.out.println(“Element is not found!” );
To implement a binary search in Java, you can follow these steps:
- Sort the array: Binary search requires the array to be sorted in ascending order for efficient searching. You can use the
Arrays.sort()method or any other sorting algorithm to sort the array. - Define the binary search method: Create a method that performs the binary search. This method should take the sorted array and the target value as parameters and return the index of the target value if found, or -1 if not found.
- Implement the binary search algorithm: Inside the binary search method, use a loop to divide the search space in half until the target value is found or the search space is exhausted. Compare the target value with the middle element of the current search space and adjust the search space accordingly.
Binary search is used to search a key element from multiple elements. Binary search is faster than linear search.
In case of binary search, array elements must be in ascending order. If you have unsorted array, you can sort the array using Arrays.sort(arr) method.
To implement a binary search in Java, you can follow these steps:
- Ensure that the array is sorted in ascending order. Binary search requires a sorted array to work correctly.
- Define a method that takes the sorted array, the target element to search for, and the indices of the subarray to search within.
- Calculate the middle index of the subarray by taking the average of the start and end indices:
int mid = (start + end) / 2. - Compare the target element with the element at the middle index:
- If they are equal, return the middle index as the position of the target element.
- If the target element is less than the middle element, recursively call the binary search method on the left half of the subarray by updating the
endindex tomid - 1. - If the target element is greater than the middle element, recursively call the binary search method on the right half of the subarray by updating the
startindex tomid + 1.
- Repeat steps 3-4 until the target element is found or the subarray is exhausted (i.e.,
startbecomes greater thanend). - If the target element is not found, return -1 to indicate that it doesn’t exist in the array.
Here’s an example implementation of the binary search algorithm in Java:
<span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">BinarySearch</span> {
<span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-type">int</span> <span class="hljs-title function_">binarySearch</span><span class="hljs-params">(<span class="hljs-type">int</span>[] arr, <span class="hljs-type">int</span> target)</span> {
<span class="hljs-keyword">return</span> binarySearch(arr, target, <span class="hljs-number">0</span>, arr.length - <span class="hljs-number">1</span>);
}
<span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-type">int</span> <span class="hljs-title function_">binarySearch</span><span class="hljs-params">(<span class="hljs-type">int</span>[] arr, <span class="hljs-type">int</span> target, <span class="hljs-type">int</span> start, <span class="hljs-type">int</span> end)</span> {
<span class="hljs-keyword">if</span> (start > end) {
<span class="hljs-keyword">return</span> -<span class="hljs-number">1</span>; <span class="hljs-comment">// Target element not found</span>
}
<span class="hljs-type">int</span> <span class="hljs-variable">mid</span> <span class="hljs-operator">=</span> (start + end) / <span class="hljs-number">2</span>;
<span class="hljs-keyword">if</span> (arr[mid] == target) {
<span class="hljs-keyword">return</span> mid; <span class="hljs-comment">// Target element found</span>
} <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (arr[mid] > target) {
<span class="hljs-keyword">return</span> binarySearch(arr, target, start, mid - <span class="hljs-number">1</span>); <span class="hljs-comment">// Search left half</span>
} <span class="hljs-keyword">else</span> {
<span class="hljs-keyword">return</span> binarySearch(arr, target, mid + <span class="hljs-number">1</span>, end); <span class="hljs-comment">// Search right half</span>
}
}
<span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">main</span><span class="hljs-params">(String[] args)</span> {
<span class="hljs-type">int</span>[] arr = {<span class="hljs-number">2</span>, <span class="hljs-number">5</span>, <span class="hljs-number">8</span>, <span class="hljs-number">12</span>, <span class="hljs-number">16</span>, <span class="hljs-number">23</span>, <span class="hljs-number">38</span>, <span class="hljs-number">56</span>, <span class="hljs-number">72</span>, <span class="hljs-number">91</span>};
<span class="hljs-type">int</span> <span class="hljs-variable">target</span> <span class="hljs-operator">=</span> <span class="hljs-number">23</span>;
<span class="hljs-type">int</span> <span class="hljs-variable">result</span> <span class="hljs-operator">=</span> binarySearch(arr, target);
<span class="hljs-keyword">if</span> (result == -<span class="hljs-number">1</span>) {
System.out.println(<span class="hljs-string">"Element not found in the array."</span>);
} <span class="hljs-keyword">else</span> {
System.out.println(<span class="hljs-string">"Element found at index: "</span> + result);
}
}
}
The binary search algorithm has a time complexity of O(log n), where n is the number of elements in the array. This makes it an efficient search algorithm for large sorted arrays.
Regarding the types of binary search, there are two commonly used variations:
- Iterative Binary Search: This implementation of binary search uses a loop to perform the search. It iteratively updates the start and end indices based on the comparison with the middle element until the target element is found or the subarray is exhausted.
- Recursive Binary Search: This implementation of binary search uses a recursive function to perform the search. It recursively calls itself with updated start and end indices until the target element is found or the subarray is exhausted. The example provided above demonstrates the recursive approach.
Java’s Arrays class offers the ‘binarySearch ()’ method, which executes a binary search on the specified Array. Binary Search Example in Java using Arrays.binarySearch()
- import java.util.Arrays;
- class BinarySearchExample2{
- public static void main(String args[]){
- int arr[] = {10,20,30,40,50};
- int key = 30;
- int result = Arrays.binarySearch(arr,key);
- if (result < 0)
- System.out.println(“Element is not found!” );
