Binary search completion state

Whenever I perform a binary search iteratively, I always get confused whether to use while (low < high) or while(low <= high) .

Although both will work, can someone tell me what could be the practical advantage of one over the other?

+5
source share
1 answer

The two termination conditions that you publish are often used depending on whether the low and high are inclusive or exclusive. If your restrictions are enabled, then when low = high, one element remains in the array for verification, and the inner loop should start at another time. Thus, checking whether low & le; high fits. On the other hand, if low is inclusive and high is exceptional, then when low = high, you have exhausted all the elements and you are done, so the form test low <high ​​is more suitable.

+2
source

Source: https://habr.com/ru/post/1242490/


All Articles