-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArraySearch.java
More file actions
37 lines (29 loc) · 896 Bytes
/
ArraySearch.java
File metadata and controls
37 lines (29 loc) · 896 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
34
35
36
37
package algorithms.sorts;
/**
*
* @author khalil2535
*/
public class ArraySearch {
public static int numberOfCompares = -1;
public static int numberOfSwaps = -1;
public static <E extends Comparable<E>> int binarySearch(E[] array, E number) {
numberOfCompares = 0;
numberOfSwaps = 0;
int lowerBound = 0;
int upperBound = array.length;
while (lowerBound < upperBound) {
final int currentIndex = lowerBound + upperBound / 2;
numberOfCompares++;
if (number.compareTo(array[currentIndex]) == 0) {
return currentIndex;
} else if (number.compareTo(array[currentIndex]) < 0) {
lowerBound = currentIndex + 1;
} else {
upperBound = currentIndex - 1;
}
}
return -1;
}
private ArraySearch() {
}
}