1. Home
  2. Explore
  3. Computer Science
  4. Binary Search Algorithm

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Binary Search Algorithm

Speaker 1Speaker 2

Binary Search Algorithm

4:43
0:00-4:43
  1. Simon

    Binary search is one of the most important algorithms out there. It lets you quickly find a target value in a sorted array, or look up a word in a dictionary.

  2. Maria

    It sounds simple, but I've heard it's surprisingly easy to get wrong. A 1988 study found that only one in four textbooks had a correct implementation.

  3. Simon

    Right, and even Java's own library had a bug that went unnoticed for over nine years. The issue was an overflow in calculating the middle index. So let's start from the basics and build up carefully.

  4. Maria

    So how does the algorithm work? Say we have a sorted array of size 7, indices 0 to 6, and we're looking for the target value 10.

  5. Simon

    We look at the middle element. If it's equal to the target, we're done. Otherwise, we eliminate half the array. For example, if the middle is 6 and target is 10, since the array is sorted, 10 must be to the right. So we focus on indices 4 to 6, and repeat.

  6. Maria

    And eventually you either find 10 at index 5, or if the target isn't there, the search range becomes empty and we return -1.

  7. Simon

    Exactly. But the tricky part is computing the middle index. A lot of people use (L+R)/2, but that can overflow if L and R are large integers. In languages like C++ or Java, int holds up to about 2 billion, and adding two such values overflows.

  8. Maria

    So what's the safe formula? I've seen L + (R-L)/2.

  9. Simon

    Right. Since R >= L, the difference R-L fits in the type. Then we do L + (R-L)/2, which avoids overflow. In C++ and Java, integer division automatically floors. In Python, you'd use double slash.

  10. Maria

    Let's see the pseudocode: initial range is from 0 to n-1. While Left <= Right, we compute mid = L + (R-L)/2. If a[mid] equals target, return mid. Otherwise, if target is greater, we set L = mid+1, else set R = mid-1. If we exit the loop, return -1.

  11. Simon

    That's the classic version. But binary search isn't limited to finding an exact match. For example, suppose we have an array and want the first value that is >= X. That's called lower bound.

  12. Maria

    I can see why the simple approach wouldn't work. If we find an element that's >= X, we can't just return it, because there might be a smaller one to the left.

  13. Simon

    Exactly. So we keep an extra variable ans, initially a sentinel like -1 or infinity. When we see a[mid] >= X, we update ans to mid and then search left for a possibly better one by setting R = mid-1. If a[mid] < X, we search right by setting L = mid+1.

  14. Maria

    So that way we find the leftmost index satisfying the condition. And if no such element exists, ans remains the sentinel.

  15. Simon

    Right. This pattern of 'first true' in a sequence of falses then trues is key. You can also find the last true by mirroring the logic. The key is to think in terms of a predicate that is false for a prefix and true for a suffix, or vice versa.

  16. Maria

    Like in the rotated array problem. We have a sorted array that's been rotated, and we want the smallest element. The challenge is that the array isn't fully sorted.

  17. Simon

    But we can still use binary search. Consider the array [6,7,...,19,2,3]. The split is between the larger numbers from the original suffix and the smaller ones from the original prefix. If we compare each element with the last element, say a[mid] > a[last], then it belongs to the left part; otherwise it's in the right part.

  18. Maria

    So we look for the first false when comparing with the last element. That gives us the start of the smaller part, which is the minimum.

  19. Simon

    Exactly. In general, binary search works as long as you can split the array into two parts based on a condition. Another example is finding a peak: an element that is larger than its neighbors. The array increases then decreases. We can check if a[mid] > a[mid-1] (treating a[-1] as -infinity) and look for the last true.

  20. Maria

    And binary search also works on real numbers. To find the square root of 2, we can search in [0,2], check mid^2 against 2, and narrow down until the interval is small enough.

  21. Simon

    Right. With floats, we don't have integer indices, so we just set L = mid or R = mid depending on the comparison, and stop when R-L is smaller than the desired precision.

  22. Maria

    So to sum up: binary search is a powerful tool for sorted arrays and beyond. The key is to think about the condition that splits the search space and use it to decide which half to explore.

  23. Simon

    Exactly. And always use the safe mid formula. Whether you're looking for an exact target, a lower bound, or a peak, the same principles apply. Happy searching!

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent