Written by Sai Sandeep Thota on August 30, 2013 in Java > Programming

Java Program to implement Binary Search

GET ALERTS:

Get our Latest updates delivered to your mailbox!

In this Java Program we are going to implement Binary Search. We have already written C Program to implement Binary Search, you can check it here. Binary Search is also known as half-interval search. Its time complexities: Best Case: O(1), Average Case: O(log n), Worst Case: O(log n).

We are populating the Array with the elements and use key variable to search for an element. Then we call the search method by passing array, number of elements (n) and key. We are using a for loop to iterate over the array to find the key element.

Java Program to implement Binary Search

import java.util.Scanner;

class search {
	void search(int a[], int n, int key)
	{
		int flag=0,p=0;
		for(int i=0;i<n;i++)
		{
			if(a[i]==key)
			{
				flag=1;
				p=i;
			}
		}
		if(flag==1)
		{
			System.out.println("Key element "+key+" is found at position "+(p+1));
		}
		else
		{
			System.out.println("Key element "+key+" is not found!!");
		}
	}
}

class binarySearch {

	public static void main(String args[])
	{
		int myArray[] = new int[10];
		int n, key;
		Scanner get = new Scanner(System.in);
		System.out.print("Enter Number of Elements:");
		n = get.nextInt();
		System.out.println("Enter "+n+" elements into the Array:");
		for(int i=0;i<n;i++)
		{
			myArray[i] = get.nextInt();
		}
		System.out.println("Enter Element to be Searched:");
		key = get.nextInt();
		search obj = new search();
		obj.search(myArray, n, key);
	}
}

Download Source Code

Output:
java_binary_search

{ 0 comments… add one now }

Leave a Comment

Previous post:

Next post: