Welcome to today's lesson! We're diving into Binary Search, a clever technique for locating specific elements within a sorted list. We can find the targeted item by repeatedly dividing the search interval in half. It's akin to flipping through a dictionary — instead of going page by page, you'd start in the middle, then narrow down the section in half until you find your desired word.
Binary Search begins at the midpoint of a sorted list, halving the search area at each step until it locates the target.
Let's search for the number 8 in a sorted list: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10. This list has 10 elements with indices 0 to 9.
To find the midpoint: mid = start + (end - start) / 2 = 0 + (9 - 0) / 2 = 4. The element at index 4 is 5. With an even number of elements, integer division gives us the lower middle element.
Since 8 > 5, we search the right half (indices 5 to 9). The new midpoint is index 7, which contains — target found!
