-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinary_Search_input.java
More file actions
48 lines (47 loc) · 1.16 KB
/
Binary_Search_input.java
File metadata and controls
48 lines (47 loc) · 1.16 KB
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
41
42
43
44
45
46
47
48
import java.util.Scanner;
public class Binary_Search_input
{
public static void main(String[] args)
{
int c=0,n;
Scanner t= new Scanner(System.in);
System.out.println("enter number of elemets in array");
n=t.nextInt();
int ar[]= new int[n];
System.out.println("Enter the sorted array: ");
for (int a=0 ; a<n; a++)
{
ar[a]= t.nextInt();
}
System.out.println("enter element to be searched");
int s= t.nextInt();
int start=0;
int end= n-1;
int mid = 0;
while (start <= end)
{
mid=(start+end)/2;
if(ar[mid] == s)
{
c++;
break;
}
else if (ar[mid] < s)
{
start = mid+1;
}
else if (ar[mid] > s)
{
end = mid-1;
}
}
if (c>0)
{
System.out.println("item found at position "+(mid+1));
}
else
{
System.out.println("search failed");
}
}
}