javacodex.com
Java Examples
Java Examples
memu home questions

Binary Search On Array

This java example shows how to perform a binary search of an element in an array using the Arrays class.

The Array must be sorted first.

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: the index of the first element greater than the key, or a.length if all elements in the array are less than the specified key. Note that this guarantees that the return value will be >= 0 if and only if the key is found.

Source: (MySearch.java)

import java.util.Arrays;
 
public class MySearch {
 
  public static void main(String[] args) {
 
    int numbers[] = {2,4,6,8,1,3,5,7,9};
 
    Arrays.sort(numbers);
 
    int search = 5;
 
    int results = Arrays.binarySearch(numbers,search);
    System.out.println("Result of binary search of 5 is : " + results);
 
    search = 100;
    results = Arrays.binarySearch(numbers,search);
    System.out.println("Result of binary search of 100 is : " + results);
 
  }
}
 

Output:

# java MySearch
Result of binary search of 5 is : 4
Result of binary search of 100 is : -10

Contact: javacodex@yahoo.com