Binary Search in Java

For the binary search program in Java if the array values are not defined already it will ask the user first to enter the size of the array. Then the user will enter array elements one by one. After adding all the elements to array ask the user to enter the element to search in an array by using binary search.

In binary search all the array elements must be sorted already, otherwise we will need to sort them first. If the duplicate numbers are entered by the user then there is no guarantee which element will be found in the binary search.

Th program first checks whether the element is present at middle if not then the element will be compared with middle value if results greater then it is present in left sub-array otherwise present in right sub-array.

Program

Following are the example programs for binary search using different functions in Java.

Implementing recursive binary search:

By using for loop and taking middle of the array we can perform a binary search on specified array in Java.

The output should be:

Element found at index 2

2. Using Collections.binarySearch() function:

By using Collections.binarySearch() function we can perform a binary search on object collections like LinkedList or ArrayList in Java.

The output should be:

45 found at index = 2
40 not found
60 found at index = 4

3. Implementing binary search:

By using Arrays.binarySearch() function we can perform a binary search on Arrays.

The output should be:

20 not found
55 found at index 3

LEAVE A REPLY

Please enter your comment!
Please enter your name here