Home Tutorial Java Collections Arraylist Java arraylist binarysearch


Share on Google+Share on Google+
Java arraylist binarysearch
Posted on: October 23, 2009 at 12:00 AM
This section describes the use of Java binarysearch

  • It is a method for searching the array element in the given array.
  • It is a static method of the class Arrays.
  • It uses the binary search algorithm. 
  • It returns the index of the found element, but if element is not found then returns -1.
  • Array can be of any data type object.
  • Array used in binarySearch must be sorted.
  • binarsearch() method with Unsorted arrays give wrong result.
  • Array having duplicate elements when searched by binarySearch() function may return any of the duplicate element.

import java.util.Arrays;

public class binary_search {

    public static void main(String[] args) {
           int ar1[]={2,44,5,66,78,90,23,66};
           int p, key=78;
           p=Arrays.binarySearch(ar1, key);
           System.out.println("element found at index "+p);
           p=Arrays.binarySearch(ar1, key);
           System.out.println("element found at index "+p);     
element found at index 4
element found at index 6


Related Tags for Java arraylist binarysearch:

Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: October 23, 2009

Recommend the tutorial

Advertisements Advertisements