## 1. Binary search

### Binary search

When we want to determine whether an array contains a certain value (target), we usually need to iterate through the array to look at each element:

int[] array = {2, 4, 6, 10, 2, 5, 7, 9}; int targetValue = 9; for(int i = 0; i < array.length; i++) { if(array[i] == targetValue) { System.out.println("Element matches target value at index: " + i); break; } }

However, if the elements in the array are sorted, we can actually find the target value without looking at each element in the array. With an array that is sorted (say, in ascending order), we can check the element in the middle of the array. If the middle element's value equals the target, then we have successfully determined that the array contains the target value; otherwise we compare the element's value with the target value. If the element's value is greater than the target, then the target can only exist in the first half of the array (since it is sorted). Similarly, if the middle element's value is lower than the target , then the target can only exist in the second half of the array. In either case, we reduce our search space by half. We can further repeat this process and reduce our search space every time we look at the middle element in our search space. This process is called binary search, and it is a very efficient way to search for values in large arrays. (We will discuss more about efficiency at later chapters.)