https://kotlinlang.org logo
#feed
Title
# feed
e

elizarov

06/16/2019, 11:21 PM
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

Dias

06/17/2019, 9:52 AM
why does it return 0 if value is not found?
a

Alowaniak

06/17/2019, 11:33 AM
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

Pavlo Liapota

06/17/2019, 11:57 AM
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

Alowaniak

06/17/2019, 12:01 PM
Yea I just noticed, I had only equal in my mind, my bad
2 Views