add examples in java 8 (#12)
* code for chapters 3-9 in Java * code for chapters 1 in Java * code for chapter 2 in Java * missing CheckVoter for chapter 5 in Java * add missing sample output for SetCovering as a comment
This commit is contained in:
committed by
Aditya Bhargava
parent
12265a8c61
commit
4631b7a156
@@ -0,0 +1,30 @@
|
||||
public class BinarySearch {
|
||||
|
||||
// has to return boxed integer in order to comfort to interface defined in the book
|
||||
private static Integer binarySearch(int[] list, int item) {
|
||||
int low = 0;
|
||||
int high = list.length - 1;
|
||||
|
||||
while (low <= high) {
|
||||
int mid = (low + high) / 2;
|
||||
int guess = list[mid];
|
||||
if (guess == item) {
|
||||
return mid;
|
||||
}
|
||||
if (guess > item) {
|
||||
high = mid - 1;
|
||||
} else {
|
||||
low = mid + 1;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
int[] myList = {1, 3, 5, 7, 9};
|
||||
|
||||
System.out.println(binarySearch(myList, 3)); // 1
|
||||
System.out.println(binarySearch(myList, -1)); // null
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user