binary seacrch java code example
Example 1: binary search java
binary search program in java.
public class BinarySearchExample
{
public static void binarySearch(int[] arrNumbers, int start, int end, int keyElement)
{
int middle = (start + end) / 2;
while(start <= end)
{
if(arrNumbers[middle] < keyElement)
{
start = middle + 1;
}
else if(arrNumbers[middle] == keyElement)
{
System.out.println("Element found at index: " + middle);
break;
}
else
{
end = middle - 1;
}
middle = (start + end) / 2;
}
if(start > end)
{
System.out.println("Element not found!");
}
}
public static void main(String[] args)
{
int[] arrNumbers = {14,15,16,17,18};
int keyElement = 16;
int end = arrNumbers.length - 1;
binarySearch(arrNumbers, 0, end, keyElement);
}
}
Example 2: binary search
import java.util.Scanner;
public class Binarysearch {
public static void main(String[] args) {
int[] x= {1,2,3,4,5,6,7,8,9,10,16,18,20,21};
Scanner scan=new Scanner(System.in);
System.out.println("enter the key:");
int key=scan.nextInt();
int flag=0;
int low=0;
int high=x.length-1;
int mid=0;
while(low<=high)
{
mid=(low+high)/2;
if(key<x[mid])
{
high=mid-1;
}
else if(key>x[mid])
{
low=mid+1;
}
else if(key==x[mid])
{
flag++;
System.out.println("found at index:"+mid);
break;
}
}
if(flag==0)
{
System.out.println("Not found");
}
}
}