-
Notifications
You must be signed in to change notification settings - Fork 0
/
BinarySearch.java
37 lines (28 loc) · 940 Bytes
/
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
package com.sleepycoders.jlib.algorithm.search;
import java.util.Comparator;
/**
* @author Joshua Moody ([email protected])
*/
public final class BinarySearch {
public static final int NOT_FOUND = -1;
/**
* Don't let anyone instantiate this class.
*/
private BinarySearch() {}
public static <T extends Comparable<? super T>> int search(T[] data, T elem) {
return search(data, elem, Comparator.<T>naturalOrder());
}
public static <T> int search(T[] data, T elem, Comparator<? super T> cmp) {
assert data != null && cmp != null;
int low = 0;
int high = data.length - 1;
while (low <= high) {
int mid = low + (high - low) / 2;
int c = cmp.compare(elem, data[mid]);
if (c < 0) { high = mid - 1; }
else if (c > 0) { low = mid + 1; }
else { return mid; }
}
return NOT_FOUND;
}
}