Skip to main content
Library homepage
 
Engineering LibreTexts

3.9: Tracing the Code

  • Page ID
    20805
  • \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \) \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)\(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\) \(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\)\(\newcommand{\AA}{\unicode[.8,0]{x212B}}\)

    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.


    This page titled 3.9: Tracing the Code is shared under a CC BY-NC-SA 3.0 license and was authored, remixed, and/or curated by Allen B. Downey (Green Tea Press) .

    • Was this article helpful?