@@ -17,25 +17,19 @@ class BinarySearch
17
17
* @return the location of the key
18
18
**/
19
19
public static int BS (int array [], int key , int lb , int ub )
20
- { if ( lb > ub )
21
- {
20
+ {
21
+ if ( lb > ub )
22
22
return -1 ;
23
- }
23
+
24
+ int mid = (lb + ub ) / 2 ;
24
25
25
- int mid =(lb +ub )/2 ;
26
-
27
- if (key <array [mid ])
28
- {
26
+ if (key < array [mid ])
29
27
return (BS (array , key , lb , mid -1 ));
30
- }
31
- else if (key >array [mid ])
32
- {
33
- return (BS (array , key , mid +1 , ub ));
34
- }
35
- else
36
- {
37
- return mid ;
38
- }
28
+
29
+ if (key > array [mid ])
30
+ return (BS (array , key , mid + 1 , ub ));
31
+
32
+ return mid ;
39
33
}
40
34
41
35
@@ -54,22 +48,21 @@ public static void main(String[] args)
54
48
55
49
//Input
56
50
System .out .println ("Enter an array of 10 numbers : " );
57
- for ( int i = 0 ; i < 10 ; i ++ )
58
- {
59
- array [i ]= input .nextInt ();
60
- }
51
+
52
+ for ( int i = 0 ; i < 10 ; i ++ )
53
+ array [i ] = input .nextInt ();
54
+
61
55
System .out .println ("Enter the number to be searched : " );
62
- key =input .nextInt ();
56
+
57
+ key = input .nextInt ();
63
58
64
59
int index =BS (array , key , 0 , 9 );
65
- if (index !=-1 )
66
- {
67
- System .out .println ("Number found at index number : " + index );
68
- }
69
- else
70
- {
60
+
61
+ if (index != -1 )
62
+ System .out .println ("Number found at index number : " + index );
63
+ else
71
64
System .out .println ("Not found" );
72
- }
65
+
73
66
input .close ();
74
67
}
75
68
}
0 commit comments