Basic Binary Search
The middle element of the array is compared to the
target value in a binary search. If they aren't equal, the method determines
which side of the array the element is in (left or right) and repeats the same
process until it finds the element. Get an
array of Integers arr[] with size n and element e to be found. Apply Linear Search to find the element e in the array arr[]. If element e is found, print its index; if not, print -1.
Examples
Input
1:
5
5
7 9 3 1
9
Output
1:
2
Input
2:
5
5
7 9 3 1
4
Output
2:
-1
Try your Solution
Strongly recommended to Solve it on your own, Don't directly go to the solution given below.
Program or Solution
import java.util.*;
class SearchB
{
public static void main(String args[])
{
//Variable and Object Declarations
Scanner input = new Scanner(System.in);
int n,e,pos=-1;
//Getting size of Array & Declare Array arr[]
n = input.nextInt();
int arr[] = new int[n];
//Get n values to array arr[]
for(int i = 0; i<n; i++)
{
arr[i] = input.nextInt();
}
e = input.nextInt();
int left=0, right=n-1;
//Binary Search
while(left<=right)
{
int mid = (left+right)/2;
if(arr[mid]==e)
{
pos = mid;
break;
}
else if(arr[mid]>e)
{
right = mid-1;
}
else
{
left = mid+1;
}
}
System.out.println(pos);
}
}