-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinarySearch.java
65 lines (53 loc) · 1.74 KB
/
BinarySearch.java
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/*
Binary search is an efficient algorithm that finds the position of a target value within a sorted array by
repeatedly dividing the search space in half.
Average Time Complexity: O(log n)
*/
public class BinarySearch<T extends Comparable<T>> {
private final T[] items;
public BinarySearch(T[] items) {
this.items = items;
}
public int searchIterative(T key) {
int low = 0;
int high = items.length - 1;
while (low <= high) {
int mid = (low + high) / 2;
T guess = items[mid];
if (guess.compareTo(key) == 0) {
return mid;
}
if (guess.compareTo(key) > 0) {
high = mid - 1;
} else {
low = mid + 1;
}
}
return -1;
}
public int searchRecursive(T key, int low, int high) {
if (low <= high) {
int mid = (low + high) / 2;
T guess = items[mid];
if (guess.compareTo(key) == 0) {
return mid;
}
if (guess.compareTo(key) > 0) {
return searchRecursive(key, low, mid - 1);
} else {
return searchRecursive(key, mid + 1, high);
}
}
return -1;
}
public static void main(String[] args) {
Integer[] intList = new Integer[] {1, 2, 3, 4, 5, 6};
int keyInt = 4;
String[] strList = {"A", "B", "C", "D", "E", "F"};
String keyStr = "F";
int index1 = new BinarySearch<>(intList).searchIterative(keyInt);
int index2 = new BinarySearch<>(strList).searchRecursive(keyStr, 0, 5);
System.out.println(index1); // must be 3
System.out.println(index2); // must be 5
}
}