Skip to content

Instantly share code, notes, and snippets.

@Morwenn
Last active February 13, 2017 19:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Morwenn/786d82168058bc53f46fab915512cb2c to your computer and use it in GitHub Desktop.
Save Morwenn/786d82168058bc53f46fab915512cb2c to your computer and use it in GitHub Desktop.
Branchless binary search insertion
/*
* 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