10
10
public class Search {
11
11
12
12
/**
13
- * Searches an item in a sorted array in O(log n) time.
13
+ * Searches an element {@param n} in a sorted array {@param a}
14
+ * and returns its index in O(log n) time. The Index may not
15
+ * correspond to the first occurrence of the element.
14
16
*
15
17
* @param a
16
18
* @param n
@@ -21,16 +23,19 @@ public static int binarySearch(int a[], int n) {
21
23
}
22
24
23
25
public static int binarySearch (int a [], int n , int low , int high ) {
24
- int mid = (low + high ) / 2 ;
25
26
26
- if (high < low ) {
27
- return -1 ;
28
- } else if (n == a [mid ]) {
29
- return mid ;
30
- } else if (n < a [mid ]) {
31
- return binarySearch (a , n , 0 , mid - 1 );
27
+ if (low <= high ) {
28
+ int mid = (low + high ) / 2 ;
29
+
30
+ if (n == a [mid ]) {
31
+ return mid ;
32
+ } else if (n < a [mid ]) {
33
+ return binarySearch (a , n , 0 , mid - 1 );
34
+ } else {
35
+ return binarySearch (a , n , mid + 1 , high );
36
+ }
32
37
} else {
33
- return binarySearch ( a , n , mid + 1 , high ) ;
38
+ return - 1 ;
34
39
}
35
40
}
36
41
@@ -41,5 +46,9 @@ public static int binarySearch(int a[], int n, int low, int high) {
41
46
*/
42
47
public static void main (String a []) {
43
48
System .out .println (binarySearch (new int []{0 , 2 }, 2 ));
49
+ System .out .println (binarySearch (new int []{0 , 1 , 2 , 3 }, 2 ));
50
+ System .out .println (binarySearch (new int []{0 , 1 , 2 , 3 }, 3 ));
51
+ System .out .println (binarySearch (new int []{0 , 2 }, 0 ));
52
+ System .out .println (binarySearch (new int []{0 , 1 , 2 , 2 , 2 , 3 , 3 }, 2 )); // doesn't return index of first occurrence
44
53
}
45
54
}
0 commit comments