Binary Search in Java

In this tutorial you will learn about binary search in Java.

Binary search is a searching algorithm that uses divide and conquer technique. The array on which searching is to be done must be sorted in ascending order. The target element is compared with middle element. If it is less than middle element then left half is discarded and if it is greater than middle element then right half is discarded. Now a new middle element is calculated in the remaining half and again comparison is done. This process is repeated until the target element is found.

Worst and average case time complexity: O (log n)

Best case time complexity: O (1)

Binary Search in Java

 

Also Read: Linear Search in Java

 

In java we can implement binary search in two ways.

  • Using manual way
  • Using Arrays.binarySearch() method

Below I have shared example for both the ways.

Binary Search in Java

Manual Way

In this example we will implement the binary search algorithm manually.

 

Output

Enter size of array:
6
Enter the array in ascending order:
1 3 5 6 7 9
Enter element to search:
6
Element found at position 4

 

Arrays.binarySearch()

We can directly search for an element in an array by using binarySearch() method of java.util.Arrays class. This method returns the index of element if it is found otherwise returns a negative value.

 

Comment below if you found anything incorrect or have doubts related to above binary search in java programs.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.