Java Program to Implement Binary Search Algorithm

Updated on December 16, 2024
Implement binary search algorithm header image

Introduction

The Binary Search algorithm is a fundamental technique in computer science used to find the position of a specific value within a sorted array. By repeatedly dividing the search interval in half, binary search reduces the time complexity to O(log n), making it much more efficient than a simple linear search for large data sets. This method relies on a comparison approach where each step eliminates half of the remaining elements from consideration.

In this article, you will learn how to implement the Binary Search algorithm in Java through practical examples. Explore different scenarios, including searching in a basic sorted array and handling cases where the target value does not exist in the array.

Implementing Binary Search in Java

Basic Binary Search Implementation

  1. Start by defining a method that performs binary search. This method accepts a sorted array and a value to search for.

  2. Determine the initial boundaries of the search area within the array.

    java
    public static int binarySearch(int[] arr, int target) {
        int left = 0;
        int right = arr.length - 1;
    
        while (left <= right) {
            int mid = left + (right - left) / 2;
    
            if (arr[mid] == target) {
                return mid; // Target found at index mid
            } else if (arr[mid] < target) {
                left = mid + 1; // Ignore left half
            } else {
                right = mid - 1; // Ignore right half
            }
        }
        return -1; // Target not found in the array
    }
    
    • left and right are the indices defining the current search boundary. mid is calculated by averaging left and right accounting for integer division.
    • The loop continues until left exceeds right, implying that every possible location has been searched.
    • If the element at mid matches the target, the index is returned. If the value is greater or lesser, the search boundary is adjusted accordingly, either narrowing down to the right half or the left half of the array.

Testing with a Sample Array

  1. To verify the correctness of the binary search implementation, define a sorted array and use the search function.

    java
    public static void main(String[] args) {
        int[] data = {2, 5, 8, 12, 16, 23, 38, 56, 72, 91};
        int target = 23;
        int result = binarySearch(data, target);
        if (result == -1) {
            System.out.println("Element not found in the array");
        } else {
            System.out.println("Element found at index: " + result);
        }
    }
    
    • In this scenario, calling binarySearch with target set to 23, the function is expected to return the index 5, as element 23 is at position 5 in the array data.

Edge Cases Handling

  1. It's important to handle cases where the target is not present in the array or the array might be empty.

    java
    public static void main(String[] args) {
        int[] data = {2, 5, 8};
        int target = 4; // Target not present
        System.out.println("Testing with missing target: " + binarySearch(data, target));
    
        int[] emptyData = {};
        target = 10; // Searching in an empty array
        System.out.println("Testing with empty array: " + binarySearch(emptyData, target));
    }
    
    • Binary search correctly returns -1 for both the missing target and the empty array scenarios, demonstrating robustness against unexpected input.

Conclusion

Binary search in Java is a classic algorithmic problem that optimizes data retrieval times significantly, particularly useful in sorting and searching operations. By following the patterns outlined, you establish reliable procedures to incorporate binary search into your Java applications. Whether dealing with fully populated or empty data sets or searching for present and absent values, the implementation showcased assists in handling a wide array of binary search scenarios efficiently and effectively.