Java Binary Search Program

Here we will learn that how to write the code for the binary search.

In the binary search ,the input must be in he ascending order.if not then you first need to do ascending order.

Java Binary search code:

import java.util.Scanner;
public class BinarySearchProgram
{
public static void main(String[] arg)
{
int firstNumber,lastNumber,searchElement,array[],n,middle;
System.out.println("Enter the number of element");
Scanner in=new Scanner(System.in);
n=in.nextIn();
array=new int[n];
System.out.println("Enter the"+n+"number");
for(int i=0;i<n;i++)
{
array[i]=in.nextInt();
}
System.out.println("Enter the number which you want to search");
searchElement=in.nextInt();
firstNumber=0;
lastNumber=n-1;
middle=(firstNumber+lastNumber)/2;
while(firstNumber<=lastNumber)
{
if(array[middle]<searchElement)
{
firstNumber=middle+1;
}
else if(array[middle]==searchElement)
{
System.out.println(searchElement+"Element found at location"+(middle+1)+".");
break;
}
else
lastNumber=middle-1;
middle=(firstNumber+lastNumber)/2;
}
if(firstNumber>lastNumber)
{
System.out.println("Element does not present in the list");
}
}
}

Output:

Enter the number of element
5
Enter the 7 number
4
8
3
9
1
Enter the number which you want to search
8
8 Element found at location 2.

Note:

The time complexity of linear search program O(log n).

sumankumar80

Hello Friends,I have written and developed this website because you can learn technology easily ,prepare for the placement and also for the any type of examination . By :Suman Kumar

Leave a Reply

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