-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinarySearch.java
More file actions
33 lines (26 loc) · 850 Bytes
/
BinarySearch.java
File metadata and controls
33 lines (26 loc) · 850 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import java.util.NoSuchElementException;
public class BinarySearch {
public static void main(String[] args) {
// Integer[] example = {10, 11, 12, 14, 15};
Integer[] example = {10, 11, 12, 14};
int index = binarySearch(example, 11);
System.out.println("index: " + index);
}
public static <T extends Comparable<? super T>> int binarySearch(T[] arr, T item) {
return binarySearch(arr, item, 0, arr.length);
}
public static <T extends Comparable<? super T>> int binarySearch(T[] arr, T item, int low, int high) {
if ( (high - low) <= 0) {
throw new NoSuchElementException();
}
int mid = (high + low) / 2;
int compare = item.compareTo(arr[mid]);
if (compare == 0) {
return mid;
} else if (compare < 0) {
return binarySearch(arr, item, low, mid);
} else {
return binarySearch(arr, item, mid, high);
}
}
}