Menu
Topics Index
...
`

Arrays BinarySearch Test - Java Example Program


Arrays BinarySearch Test
java.util.Arrays;

class  ArraysBinarySearchTest
{
    public static void main(String arg[])
    {
        int sample[] = {5, 1, 8, 0, 4, 3, 7, 6, 10, 9};
        Arrays.sort(sample); // LINE A
        int index = Arrays.binarySearch(sample, 5); // LINE B
        if (index >= 0)
        {
            System.out.println("Element 5 is found at position: " + index);
        } else
        {
            System.out.println("Element 5 is not found. It can be inserted at position: " + index);
        }
        index = Arrays.binarySearch(sample, 2); //LINE C
        if (index >= 0)
        {
            System.out.println("Element 2 is found at position: " + index);
        } else
        {
            System.out.println("Element 2 is not found. It can be inserted at position: " + index);
        }    
    }
}
OUTPUT

Element 5 is found at position: 4
Element 2 is not found. It can be inserted at position: -3

DESCRIPTION

Initially the array is not sorted, we need to sort the array before searching. Sorting is done at LINE A. At LINE B, binary search is done on the array with search key as 5. 'index' holds the position of the search key in the array. If found, position is printed else element is not found. At LINE C, we are trying to find an element which is not present in the array it returns a values less than 0 i.e. (-(insertion point) - 1) as mentioned above.

THINGS TO TRY
  • Comment LINE A and search for the key and print the result.
  • Use a different data type like float for search key and perform the binary search i.e. search for 5.0f instead of 5
  • Search for the key 14 instead of 2

© meritcampus 2019

All Rights Reserved.

Open In App