File tree Expand file tree Collapse file tree 1 file changed +53
-0
lines changed Expand file tree Collapse file tree 1 file changed +53
-0
lines changed Original file line number Diff line number Diff line change
1
+ import java .util .Scanner ;
2
+
3
+ class BinarySearch
4
+ {
5
+ public static int BS (int array [], int key , int lb , int ub )
6
+ {
7
+ if (lb >ub )
8
+ {
9
+ return -1 ;
10
+ }
11
+
12
+ int mid =(lb +ub )/2 ;
13
+
14
+ if (key <array [mid ])
15
+ {
16
+ return (BS (array , key , lb , mid -1 ));
17
+ }
18
+ else if (key >array [mid ])
19
+ {
20
+ return (BS (array , key , mid +1 , ub ));
21
+ }
22
+ else
23
+ {
24
+ return mid ;
25
+ }
26
+ }
27
+
28
+ public static void main (String [] args )
29
+ {
30
+ Scanner input =new Scanner (System .in );
31
+ int array []=new int [10 ] ;
32
+ int key ;
33
+
34
+ //Input
35
+ System .out .println ("Enter an array of 10 numbers : " );
36
+ for (int i =0 ; i <10 ;i ++ )
37
+ {
38
+ array [i ]=input .nextInt ();
39
+ }
40
+ System .out .println ("Enter the number to be searched : " );
41
+ key =input .nextInt ();
42
+
43
+ int index =BS (array , key , 0 , 9 );
44
+ if (index !=-1 )
45
+ {
46
+ System .out .println ("Number found at index number : " + index );
47
+ }
48
+ else
49
+ {
50
+ System .out .println ("Not found" );
51
+ }
52
+ }
53
+ }
You can’t perform that action at this time.
0 commit comments