Skip to content

Commit b5fbc46

Browse files
committed
Non recursive binary search added
1 parent 468f490 commit b5fbc46

File tree

1 file changed

+32
-4
lines changed

1 file changed

+32
-4
lines changed

src/main/java/com/rampatra/arrays/searching/BinarySearch.java

+32-4
Original file line numberDiff line numberDiff line change
@@ -13,11 +13,11 @@ public class BinarySearch {
1313
* and returns its index in O(log n) time. The Index may not
1414
* correspond to the first occurrence of the element.
1515
*
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
1919
*/
20-
public static int binarySearch(int[] a, int n) {
20+
private static int binarySearch(int[] a, int n) {
2121
return binarySearch(a, n, 0, a.length - 1);
2222
}
2323

@@ -38,6 +38,28 @@ public static int binarySearch(int[] a, int n, int low, int high) {
3838
}
3939
}
4040

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+
4163
/**
4264
* Driver for testing.
4365
*
@@ -49,5 +71,11 @@ public static void main(String[] a) {
4971
System.out.println(binarySearch(new int[]{0, 1, 2, 3}, 3));
5072
System.out.println(binarySearch(new int[]{0, 2}, 0));
5173
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));
5280
}
5381
}

0 commit comments

Comments
 (0)