Skip to content

Instantly share code, notes, and snippets.

@cleure
Created August 4, 2016 16:02
Show Gist options
  • Save cleure/bcaa7d1f55e45cf83d7c05775720f4f3 to your computer and use it in GitHub Desktop.
Save cleure/bcaa7d1f55e45cf83d7c05775720f4f3 to your computer and use it in GitHub Desktop.
Branchless sorting network for a 6 element array
/**
* Swap two positive 32-bit integers, to sorted order (ascending).
*
* @param int32_t a
* @param int32_t b
* @return int32_t
**/
static inline void _pswap32a(int32_t *input, size_t i1, size_t i2)
{
int32_t a, b, c1, c2,
v1 = input[i1],
v2 = input[i2];
// Subtract value2 from value1, and grab sign bit.
c1 = (v1 - v2) >> 31 & 1;
// Inverse of sign bit.
c2 = c1 ^ 1;
// Calculate min of value1 and value2.
a = (v1 * c1) + (v2 * c2);
// Calculate max of value1 and value2.
b = (v1 * c2) + (v2 * c1);
// Swap.
input[i1] = a;
input[i2] = b;
}
/**
* Sorting network, to sort an array of 6 elements. The swap function
* this uses does not branch.
*
* @param int32_t[6]
*/
void sort6(int32_t array[6])
{
_pswap32a(array, 1, 2);
_pswap32a(array, 0, 2);
_pswap32a(array, 0, 1);
_pswap32a(array, 4, 5);
_pswap32a(array, 3, 5);
_pswap32a(array, 3, 4);
_pswap32a(array, 0, 3);
_pswap32a(array, 1, 4);
_pswap32a(array, 2, 5);
_pswap32a(array, 2, 4);
_pswap32a(array, 1, 3);
_pswap32a(array, 2, 3);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment