Answer
Binary Search Using Arrays.binarySearch() Method
Java
import java.util.Arrays;
public class BinarySearchUsingMethod {
public static void main(String[] args) {
int array[] = { 10, 20, 30, 40, 50 }; // Must be sorted
// Arrays.binarySearch(array, searchElement)
// Returns: index of found element, or negative if not found
System.out.println(Arrays.binarySearch(array, 30)); // → 2
System.out.println(Arrays.binarySearch(array, 10)); // → 0
System.out.println(Arrays.binarySearch(array, 99)); // → negative (not found)
}
}
Output
CODE
2
0
-6
Return Value Rules
Java
int[] arr = { 10, 20, 30, 40, 50 };
// Found: returns index (0-based)
Arrays.binarySearch(arr, 30) // → 2
// Not found: returns -(insertionPoint) - 1
Arrays.binarySearch(arr, 25) // → -3 (25 would go at index 2 → -(2)-1 = -3)
Arrays.binarySearch(arr, 99) // → -6 (99 would go at index 5 → -(5)-1 = -6)
Search in Subarray
Java
int[] arr = { 5, 10, 20, 30, 40, 50, 60 };
// Search only between index 2 and 5 (inclusive)
int result = Arrays.binarySearch(arr, 2, 5, 30); // → 3
Search String Array
Java
String[] names = { "Alice", "Bob", "Charlie", "David" }; // must be sorted
int idx = Arrays.binarySearch(names, "Charlie");
System.out.println("Found at: " + idx); // → 2
Full Example with Validation
Java
import java.util.Arrays;
public class BinarySearchComplete {
public static void main(String[] args) {
int[] arr = { 10, 20, 30, 40, 50 };
int target = 30;
int result = Arrays.binarySearch(arr, target);
if (result >= 0)
System.out.println(target + " found at index " + result);
else
System.out.println(target + " not found in array");
}
}
Comparison: Manual vs Method
| Manual Implementation | Arrays.binarySearch() | |
|---|---|---|
| Code | ~20 lines | 1 line |
| Sorted required | Yes | Yes |
| Returns | Custom message | Index or negative |
| Flexibility | High | Medium |
