Search code examples
binary-search

Does binary search in any case work with physical numbers themselves? Excluding 0


If there is a list in numerical order, (1 - 10) will binary search work with it? If the answer is no, can I have an explanation why it won't?


Solution

  • Binary search works with any array that is sorted.

    Take searching for 3 as an example; assume we have a list of numbers from 1 to 10.

    1 2 3 4 5 6 7 8 9 10
    

    First, we divide it in two.

    1 2 3 4 5      6 7 8 9 10
    

    Since 3 is less than 6, we go with the first half.

    1 2 3      4 5
    

    Since 3 is less than 4, we go with the first half again.

    1 2    3
    

    Since 3 is equal to 3, we go with the second half. And we have found 3.