File tree Expand file tree Collapse file tree 1 file changed +49
-0
lines changed Expand file tree Collapse file tree 1 file changed +49
-0
lines changed Original file line number Diff line number Diff line change
1
+ import java .util .Scanner ;
2
+ public class Main
3
+ {
4
+ static int Binary_search (int a [],int n ,int element )
5
+ {
6
+ int l =0 ,r =n -1 ;
7
+
8
+ while (l <=r )
9
+ {
10
+ int mid =(l +r )/2 ;
11
+ if (element ==a [mid ])
12
+ {
13
+ return mid ;
14
+ }
15
+ else if (element < a [mid ])
16
+ {
17
+ r =mid -1 ;
18
+ }
19
+ else
20
+ {
21
+ l =mid +1 ;
22
+ }
23
+ }
24
+ return -1 ;
25
+ }
26
+ public static void main (String [] args ) {
27
+ int n ;
28
+ System .out .print ("Enter the size of array:" );
29
+ Scanner sc =new Scanner (System .in );
30
+ n =sc .nextInt ();
31
+ int [] a =new int [n ];
32
+ for (int i =0 ;i <n ;i ++)
33
+ {
34
+ a [i ]=sc .nextInt ();
35
+ }
36
+ int element ;
37
+ System .out .print ("Enter element:" );
38
+ element =sc .nextInt ();
39
+ int res =Binary_search (a ,n ,element );
40
+ if (res ==-1 )
41
+ {
42
+ System .out .print ("Element not found" );
43
+ }
44
+ else
45
+ {
46
+ System .out .print ("Element found at index" +res );
47
+ }
48
+ }
49
+ }
You can’t perform that action at this time.
0 commit comments