Created
February 11, 2016 14:08
-
-
Save gravitino/ad1c39a93db082491174 to your computer and use it in GitHub Desktop.
Inplace Permutation
This file contains 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
#ifndef INPLACE_ALGORITHMS | |
#define INPLACE_ALGORITHMS | |
template< | |
class value_t, | |
class index_t> | |
void permute( | |
value_t * data, | |
index_t * perm, | |
index_t length) { | |
for (index_t i = 0; i < length; i++) { | |
if (perm[i] >= length) { | |
// unmark | |
perm[i] -= length; | |
continue; | |
} | |
auto v = data[i]; | |
auto j = perm[i]; | |
while (j != i) { | |
// swap | |
auto tmp = data[j]; data[j] = v; v = tmp; | |
// hop and mark as visited | |
perm[j] += length; | |
j = perm[j]-length; | |
} | |
data[i] = v; | |
} | |
} | |
#endif |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment