Skip to main content
Engineering LibreTexts

3.9: Tracing the Code

  • Page ID
    20805
  • To see how binary search works, it’s helpful to add the following print statement at the beginning of the loop:

    System.out.println(low + ", " + high);
    

    If we invoke binarySearch like this:

    Card card = new Card(11, 0);
    System.out.println(binarySearch(cards, card));
    

    We expect to find this card at position 10. Here is the result:

    0, 51
    0, 24
    0, 11
    6, 11
    9, 11
    10
    

    If we search for a card that’s not in the array, like new Card(15, 1), which is the “15 of Diamonds”, we get the following:

    0, 51
    26, 51
    26, 37
    26, 30
    26, 27
    -1
    

    Each time through the loop, we cut the distance between low and high in half. After k iterations, the number of remaining cards is \(52 / 2^k \). To find the number of iterations it takes to complete, we set \( 52/ 2^k = 1\) and solve for \(k\). The result is \( \log_{2}{52} \), which is about \(5.7\). So we might have to look at 5 or 6 cards, as opposed to all 52 if we did a sequential search.

    More generally, if the array contains \(n\) elements, binary search requires \( \log_{2}{n} \) comparisons, and sequential search requires \(n\). For large values of \(n\), binary search can be much faster.

    • Was this article helpful?