Skip to content

Commit 06c803f

Browse files
author
Cody Gagnon
committed
Added recursive method
1 parent 1a7900e commit 06c803f

1 file changed

Lines changed: 22 additions & 1 deletion

File tree

‎class_code/11-22-custom_binary_search/BinarySearch.java‎

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,17 @@
11

22
public class BinarySearch {
3+
public static void main(String[] args) {
4+
int[] numbers = {-1, 0, 5, 11, 18, 29, 53, 57, 61, 64, 78, 82, 85, 89, 93};
5+
System.out.println(binarySearchWithLoop(numbers, 86));
6+
System.out.println(binarySearchRecursive(numbers, 86, 0, numbers.length - 1));
7+
}
38

4-
public static int binarySearch(int[] a, int value) {
9+
public static int binarySearchWithLoop(int[] a, int value) {
510
// With a loop
611
int first = 0, last = a.length - 1;
712
while(first <= last) {
813
int mid = (first + last) / 2;
14+
System.out.println("mid = " + mid );
915
//compare a[mid] with value
1016
if (a[mid] < value) {
1117
first = mid + 1;
@@ -17,5 +23,20 @@ public static int binarySearch(int[] a, int value) {
1723
}
1824
return -(first) - 1; // -insertion point - 1
1925
}
26+
public static int binarySearchRecursive(int[] a, int value, int first, int last) {
27+
if (first > last) {
28+
return -first -1;
29+
} else {
30+
int mid = (first + last) / 2;
31+
System.out.println("mid = " + mid );
32+
if (a[mid] < value) {
33+
return binarySearchRecursive(a, value, mid + 1, last);
34+
} else if (a[mid] > value) {
35+
return binarySearchRecursive(a, value, first, mid - 1);
36+
} else {
37+
return mid;
38+
}
39+
}
40+
}
2041

2142
}

0 commit comments

Comments
 (0)