Let's learn java programming language with easy steps

Monday, 26 March 2018

Binary Search Program in Java

Binary Search in Java Program

Write a Java Program for Binary Search

Here we are gonna to see binary search program in java which is mostly asked in core java interviews.

Binary search is used to search specified element from the list of multiple elements. Binary search algorithm is a algorithm that find the position of a targate value within a sorted array. It compares the targate value to the middle element of the array.

Binary search is also known as half-interval search or binary chop or logarithmic search.

Let's see binary search java example.

Write a Java Program for Binary Search 

This is the simple implementation of binary search using java program. Here we are going to use Scanner class for taking input from the user e.g number of elements, values of elements, and key element for searching.

import java.util.Scanner;
class BinarySearchExample
public static void main(String args[])
int num, array[], counter, item, first, last, middle;

Scanner sc = new Scanner(System.in);
System.out.println("Enter number of elements");
num = sc.nextInt();

array = new int[num];//creating array and declare number of elements

System.out.println("Enter " +num+ " Elements ");

for(counter = 0; counter < num; counter++)
array[counter] = sc.nextInt();

System.out.println("Enter key element for searching ");
item = sc.nextInt();
first = 0;
last = num - 1;
middle = (first + last)/2;

while(first <= last)

if(array[middle] < item )
first = middle + 1;

else if(array[middle] == item)
System.out.println(item+ " found at location " + (middle + 1));

last = middle - 1;

middle = (first + last)/2;

if(first > last)
System.out.println(item+ " not found");

Output: Enter number of elements
             Enter 5 elements
             Enter key element for searching
             89 found at location 3

There is another way we can perform binary search operationg using java program.

Binary Search Example

This is another java program for binary search by using Arrays.binarySearch() method.

We have to import java.util.Arrays class.

import java.util.Arrays;
class BinarySearch2
public static void main(String args[])
int elements[] = {14, 65, 89, 91, 96};
int keyElement = 89;

int search = Arrays.binarySearch(elements, keyElement);
if(search < 0)
System.out.println(" Element not found ");
System.out.println(" Element is found at index " + search);

Output: Element is found at index 2

You can check other java programs, link given below

Linear Search Program in Java
Bubble Sort Program in Java 
Java Array Programming Interview Questions 

Here we discussed some most important binary search programs in java which will help you in java interviews.



Facebook Page Likes

Follow javatutorial95 on Google+

Follow javatutorial95 on twitter

Popular Posts

Get Updates By Email