Binary SearchΒΆ
A binary search can only be used if the data is sorted.
It compares a target value to the value in the middle of a range of indices. If the value isn’t found it looks again in either the left or right half of the current range. Each time through the loop it eliminates half the values in the search area until either the value is found or there is no more data to look at. Click on this Binary Search Animation to see how it works.
Binary search calculates the middle index as left + right / 2
where left starts out at 0 and right starts out at the array length  1 (the index of the last element). Remember that integer division gives an integer result so 2.5 becomes 2. It compares the value at the middle index with the target value (the value you are searching for). If the target value is less than the value at the middle it sets right to middle minus one. If the target value is greater than the value at the middle it sets left to middle plus one. Otherwise the values match and it returns the middle index. It also stops when left is greater than right which indicates that the value wasn’t found and it returns 1.
The code for binarySearch
below is from the AP CS A course description.
To see this executing using the Java Visualizer click on the following link: BinarySearch Ex

1231: Which will cause the shortest execution of a binary search looking for a value in an array of integers?
 (A) The value is the first one in the array
 This would be true for sequential search, not binary.
 (B) The value is in the middle of the array
 If the value is in the middle of the array the binary search will return after one iteration of the loop.
 (C) The value is the last one in the array
 How would that be the shortest in a binary search?
 (D) The value isn't in the array
 This is true for the longest execution time, but we are looking for the shortest.
 (A) I only
 You can use a binary search on any type of data that can be compared, but the data must be in order.
 (B) I and II
 You can use a binary search on any type of data that can be compared.
 (C) II only
 The only requirement for using a Binary Search is that the values must be ordered.
 (D) II and III
 The array can contain duplicate values.
1232: Which of the following conditions must be true in order to search for a value using binary search?
I. The values in the array must be integers.
II. The values in the array must be in sorted order.
III. The array must not contain duplicate values.

1233: How many times would the while loop execute if you first do int[] arr = {2, 10, 23, 31, 55, 86} and then call binarySearch(arr,55)?
 (A) 2
 It will first compare with the value at index 2 and then index 4 and then return 4.
 (B) 1
 This would be true if we were looking for 23.
 (C) 3
 This would be true if we were looking for 31.