Java Binary Search

  1. Arrays.binarySearch() Overview
  2. Java Program for Binary Search
Note

If you want to understand Binary Search in detail then refer to the binary search algorithm article.

Java provides us with a ready to use function Arrays.binarySearch() so that we don’t have to implement the function ourselves. It is a very simple to use and efficiently implemented method and it is not prone to errors.

Arrays.binarySearch() Overview

Syntax

public static int binarySearch(T arr, T key )

T can be any of the following: int, float, short, long, byte, char, double, and even a user-defined Object as well.

Just like our implemented binary search, it also requires the array to be sorted otherwise the results are undefined. It searches the array using the binary search algorithm and finds the index of the target element. If there are multiple occurrences of the target element then it can return the index of any one of them.

Parameters

Arr The input array
Key The target element we are searching for.

Return

If it finds the target element then it returns its index. Otherwise, it returns beg - 1 where beg is the starting index of the array search space.

import java.util.Arrays;

class BinarySearchExample{
    public static void main(String args[]){
        int arr[] = {1,2,3,4,5};
        int key = 2;
        int result = Arrays.binarySearch(arr,key);
        if (result < 0)
            System.out.println("Element is not found!");
        else
            System.out.println("Element is found at index: "+result);
    }
}

Output:

Element is found at index: 1
Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Java Algorithm

  • Java Binary Search Interactive and Recursive