Binary Search
import java.lang.*;
import java.util.*;
import java.io.*;
class Search
{
public int binarysearch(int[]a,int key)
{
int f=1;
int low=0;
int high=a.length-1;
int mid=(low+high)/2;
while(low<=high)
{
if(a[mid]==key)
{
f=0;
break;
}
if(a[mid]<key)
low=mid+1;
else
high=mid-1;
mid=(low+high)/2;
}
return(f);
}
}
class Binarysearch
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
Search s=new Search();
int[]a;
int i,k,n;
int f=1;
System.out.println("Binary search");
System.out.println("enter your choice");
System.out.println("Enter the size of array");
n=sc.nextInt( );
a=new int[n];
System.out.println("Enter the elements");
for(i=0;i<n;i++)
a[i]=sc.next();
System.out.println("Enter the element to search:");
k=sc.nextInt();
int c=s.binarysearch(a,k);
if(c==0)
System.out.println("The element is found");
else
System.out.println("The elements is not found");
}
}
Output:
javac Binarysearch.java
java Binarysearch
BINARY SEARCH
Enter your choice
Enter the size of array
5
Enter the elements into the array
2
4
1
8
9
Enter the element to search
8
The element is found
Output:
javac Binarysearch.java
java Binarysearch
BINARY SEARCH
Enter your choice
Enter the size of array
5
Enter the elements into the array
2
4
1
8
9
Enter the element to search
10
The element not found