Created
June 21, 2017 11:28
-
-
Save bit-hack/5487a905c400d31d24913148c816a0b5 to your computer and use it in GitHub Desktop.
Branchless binary search
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// based on: | |
// blog.demofox.org/2017/06/20/simd-gpu-friendly-branchless-binary-search | |
#include <cstdint> | |
#include <cstddef> | |
template <typename type_t, size_t size> | |
size_t binary_search(type_t val, const type_t (& data)[size]) { | |
size_t pos = 0; | |
size_t i = size >> 1; | |
/* check that loop gets unrolled */ | |
for (;i;i>>=1) { | |
pos += (data[pos + i] <= val) ? i : 0; | |
} | |
return pos; | |
} | |
int main() { | |
int test[] = { 0, 1, 2, 3, 4, 5, 6, 7 }; | |
return binary_search(3, test); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment