Last active
February 13, 2017 19:47
-
-
Save Morwenn/786d82168058bc53f46fab915512cb2c to your computer and use it in GitHub Desktop.
Branchless binary search insertion
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
/* | |
* This function inserts first in [first+1, first+8), which is a | |
* sorted sequence. | |
*/ | |
template<typename RandomAccessIterator, typename Compare=std::less<>> | |
auto front_insert8(RandomAccessIterator first, Compare compare={}) const | |
-> void | |
{ | |
auto it = first; | |
it += compare(it[4], *first) << 2; | |
it += compare(it[2], *first) << 1; | |
it += compare(it[1], *first) << 0; | |
switch (std::distance(first, it)) | |
{ | |
// rotate_left rotates the sequence beginning at the passed | |
// iterator by N positions to the left | |
case 1: rotate_left<2>(first); break; | |
case 2: rotate_left<3>(first); break; | |
case 3: rotate_left<4>(first); break; | |
case 4: rotate_left<5>(first); break; | |
case 5: rotate_left<6>(first); break; | |
case 6: rotate_left<7>(first); break; | |
case 7: rotate_left<8>(first); break; | |
default: break; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment