-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinarySearch.java
More file actions
40 lines (40 loc) · 926 Bytes
/
Copy pathBinarySearch.java
File metadata and controls
40 lines (40 loc) · 926 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import java.util.Scanner;
class BinarYSearch
{
public static void main(String XYZ[])
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int arr[]=new int[n];
int i=0;
for(i=0;i<n;i++)
{
arr[i]=sc.nextInt();
}
System.out.println("Enter the number to be searched:");
int value=sc.nextInt();
int low=0,high=n-1;
int mid;
while(low<=high)
{
mid=(low+high)/2;
if(arr[mid]==value)
{
System.out.println("Element found at position:"+mid);
break;
}
else if(arr[mid]>value)
{
high=mid-1;
}
else
{
low=mid+1;
}
}
if(low>high)
{
System.out.println("Element not found!");
}
}
}