Java Reference
In-Depth Information
0 0 0 0 0 0 0 0 0 0 0
guess: 50
response/hint: higher
conclusion: 51 <= number <= 100
0 0 0 0 0 0 0 0 0 0 0
guess: 75
response/hint: lower
conclusion: 51 <= number <= 74
0 0 0 0 0 0 0 0 0 0 0
guess: 62
response/hint: higher
conclusion: 63 <= number <= 74
0 0 0 0 0 0 0 0 0 0 0
guess: 68
response/hint: higher
conclusion: 69 <= number <= 74
0 0 0 0 0 0 0 0 0 0 0
guess: 71
response/hint: higher
conclusion: 72 <= number <= 74
0 0 0 0 0 0 0 0 0 0 0
guess: 73
response/hint: correct!
Figure 13.1
Passes of a binary search for a number between 1 and 100
// binary search on an array
int[] numbers = {-3, 2, 8, 12, 17, 29, 44, 58, 79};
int index = Arrays.binarySearch(numbers, 29);
System.out.println("29 is found at index " + index);
If you're using a list such as an ArrayList instead, you can call the static method
Collections.binarySearch to search the list of elements. If you had an
ArrayList called list containing the same elements as the array in the previous
example, the following code would similarly search the elements at indexes 4, 6, and
then 5 before assigning the value 5 to the variable index :
// binary search on an ArrayList
int index = Collections.binarySearch(list, 29);
System.out.println("29 is found at index " + index);
 
Search WWH ::




Custom Search