import java.util.Scanner;
class BinarySearch
{
public static void main(String args[])
{
int count, num, element, array[], first, last, middle;
//To capture user input
Scanner input = new Scanner(System. in );
System.out.println("Enter number of elements in array:");
num = input.nextInt();
//Creating array to store the all the numbers
array = new int[num];
System.out.println("Enter " + num + " integers:");
//Loop to store each numbers in array
for (count = 0; count < num; count++)
array[count] = input.nextInt();
System.out.println("Enter the element to be searched:");
element = input.nextInt();
first = 0;
last = num - 1;
middle = (first + last) / 2;
while (first <= last)
{
if (array[middle] < element) first = middle + 1;
else if (array[middle] == element)
{
System.out.println("Element" + element + " found at location " + (middle + 1) + ".");
break;
}
else
{
last = middle - 1;
}
middle = (first + last) / 2;
}
if (first > last)
System.out.println("Element" + element + " doesn't exist in array :(\n");
}
}Thank you, keep learning and sharing
