Write a Java program to implement binary search. Do a sorting then find the position of the element. Test Case 1 Input (stdin) 2 5 7 13 98 13 Expected Output Element found at position 4 Test Case 2 Input (stdin) 56 23 12 89 10 19 Expected Output Element not found in the tree
import java.util.Scanner;
public class TestClass
{
public static void main(String args[])
{
int counter,temp,num=5, item, array[], first, last, middle;
Scanner input = new Scanner(System.in);
array = new int[num];
for (counter = 0; counter < num; counter++)
array[counter] = input.nextInt();
for (int i = 0; i < num; i++)
{
for (int j = i + 1; j < num; j++)
{
if (array[i] > array[j])
{
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
item = input.nextInt();
first = 0;
last = num - 1;
middle = (first + last)/2;
while( first <= last )
{
if ( array[middle] < item )
first = middle + 1;
else if ( array[middle] == item )
{
System.out.println("Element found at position " + (middle + 1));
break;
}
else
{
last = middle - 1;
}
middle = (first + last)/2;
}
if ( first > last )
System.out.println("Element not found in the tree");
}
}