Binary search is a simple algorithm, but can you c...
# feed
e
Binary search is a simple algorithm, but can you code a straightforward and correct implementation of it? It seems that it is not quite easy to figure out unless you were taught to do it. https://medium.com/@elizarov/programming-binary-search-6e999783ba5d
K 9
d
why does it return 0 if value is not found?
a
Yea I also don't get that, in the playground to try it yourself first it says "result of function is essentially equal to result of"
list.indexOfFirst { it >= value }.takeIf { it >= 0 } ?: list.size
which would mean it should give the size of the list when not found?
But the test expects
0
when searching for
0
in
[1]
.
p
It searches for an index of first element which is more or equal to a given value. Element
1
is more than value
0
so index
0
is returned.
a
Yea I just noticed, I had only equal in my mind, my bad