@@ -13,11 +13,11 @@ public class BinarySearch {
13
13
* and returns its index in O(log n) time. The Index may not
14
14
* correspond to the first occurrence of the element.
15
15
*
16
- * @param a
17
- * @param n
18
- * @return
16
+ * @param a sorted array to be searched
17
+ * @param n number to be searched in the array
18
+ * @return index of {@param n} or {@code -1} if not present
19
19
*/
20
- public static int binarySearch (int [] a , int n ) {
20
+ private static int binarySearch (int [] a , int n ) {
21
21
return binarySearch (a , n , 0 , a .length - 1 );
22
22
}
23
23
@@ -38,6 +38,28 @@ public static int binarySearch(int[] a, int n, int low, int high) {
38
38
}
39
39
}
40
40
41
+ /**
42
+ * Non-recursive version of binary search.
43
+ *
44
+ * @param a sorted array to be searched
45
+ * @param n number to be searched in the array
46
+ * @return index of {@param n} or {@code -1} if not present
47
+ */
48
+ private static int binarySearchNonRecursive (int [] a , int n ) {
49
+ int low = 0 , high = a .length , mid ;
50
+ while (low <= high ) {
51
+ mid = (low + high ) / 2 ;
52
+ if (n == a [mid ]) {
53
+ return mid ;
54
+ } else if (n < a [mid ]) {
55
+ high = mid - 1 ;
56
+ } else {
57
+ low = mid + 1 ;
58
+ }
59
+ }
60
+ return -1 ;
61
+ }
62
+
41
63
/**
42
64
* Driver for testing.
43
65
*
@@ -49,5 +71,11 @@ public static void main(String[] a) {
49
71
System .out .println (binarySearch (new int []{0 , 1 , 2 , 3 }, 3 ));
50
72
System .out .println (binarySearch (new int []{0 , 2 }, 0 ));
51
73
System .out .println (binarySearch (new int []{0 , 1 , 2 , 2 , 2 , 3 , 3 }, 2 )); // doesn't return index of first occurrence
74
+ System .out .println ("---------" );
75
+ System .out .println (binarySearchNonRecursive (new int []{0 , 2 }, 2 ));
76
+ System .out .println (binarySearchNonRecursive (new int []{0 , 1 , 2 , 3 }, 2 ));
77
+ System .out .println (binarySearchNonRecursive (new int []{0 , 1 , 2 , 3 }, 3 ));
78
+ System .out .println (binarySearchNonRecursive (new int []{0 , 2 }, 0 ));
79
+ System .out .println (binarySearchNonRecursive (new int []{0 , 1 , 2 , 2 , 2 , 3 , 3 }, 2 ));
52
80
}
53
81
}
0 commit comments