←back to thread

386 points ingve | 1 comments | | HN request time: 0.288s | source
Show context
tromp ◴[] No.35738737[source]
The setup code to reduce the length to a 2-power can be avoided. I'm curious how well the following code performs in comparison:

    for (size_t length = end - begin; length != 0; length = (length + 1) / 2)
    {
        size_t step = length / 2;
        if (compare(begin[step], value))
            begin += step;
    }   
    return begin;
For odd lengths like 5, this splits the array in an even part of length 2, and an odd part of length 3, and then searches either part with length 3. So again there is some redundancy for non-2-powers.

While this code is simpler, it does require an extra division and increment in each loop iteration, so presumably it performs a little worse.

replies(1): >>35750752 #
teo_zero ◴[] No.35750752[source]
Doesn't this run forever? Once length reaches 1 it will never go to 0.
replies(1): >>35750942 #
1. tromp ◴[] No.35750942[source]
Oops; you're right. One possible fix is

    for (size_t length = end - begin; length != 1; length = (length + 1) / 2)
    {
        size_t step = length / 2;
        if (compare(begin[step], value))
            begin += step;
    }   
    return begin + compare(*begin, value);
but it admittedly detracts from the simplicity of the former...