Java Arrays.binarySearch(Object[] a, Object key) example

 Posted On  | Pooja Lakkihal 

In this tutorial, You will learn how to search the specified array of Object for the specified value using the binary search algorithm. Java Arrays.binarySearch(Object[] a, Object key) method returns the index of the search key.

Searches the specified array for the specified object using the binary search algorithm. The array must be sorted into ascending order according to the natural ordering of its elements (as by the sort(Object[]) method) prior to making this call.

syntax

public static int binarySearch(Object[] a, Object key)

Parameters

a - the array to be sorted.

key - the value to be searched for.

Returns

index of the search key, if it is contained in the array; otherwise, (-(insertion point) - 1). The insertion point is defined as the point at which the key would be inserted into the array.

Throws

ClassCastException - if the search key is not comparable to the elements of the array.

Java Arrays binarySearch(Object[] a, Object key) example

  • Initialize the Object array Object array[] = { 11, 0, 77, 65, 20, 2 };
  • Arrays.sort(array); It will sort the array into ascending numerical order.
  • Object key = 65; Assign the key value to be searched.
  • Arrays.binarySearch(array, key); It will search the array of Object for the specified value using the binary search algorithm.
package com.technicalkeeda;

import java.util.Arrays;

public class App {

    public static void main(String[] args) {

        Object array[] = {
            11,
            0,
            77,
            65,
            20,
            2
        };

        System.out.println("Elements in array :- ");
        for (Object number: array) {
            System.out.print(number + " ");
        }

        Arrays.sort(array);

        System.out.println("The sorted array is :- ");
        for (Object number: array) {
            System.out.print(number + " ");
        }

        System.out.println();
        Object key = 65;

        int returnValue = Arrays.binarySearch(array, key);

        System.out.println("Index value of 65 is :-  " + returnValue);
    }
}

output

Elements in array :- 
11 0 77 65 20 2 

The sorted array is :- 
0 2 11 20 65 77 

Index value of 65 is :-  4


© technicalkeeda.com 2018

 |  Find us on Google+ |  Rss Feed

Loaded in 0.0352 seconds.