Decomposing permutations into cycles with less than O(n) additional memory

Viewed 132

I am currently trying to find an algorithm that can find a cyclic decomposition of a permutation, set by this formula:

s(i) = (i / w) + (i % w) * h;

where h and w are the numbers of rows and columns of a matrix (I want to use it for in-place matrix transposition). However, the only algorithm for decomposition that I am aware of uses O(h * w) additional memory, like this:

std::vector<size_t> cycles;
std::vector<bool> visited(h * w, false);
for (size_t i = 0; i < h * w; ++i) {
  if (!visited[i]) {
    visited[i] = true;
    cycles.push_back(i);
    // I don't need complete cycles, one member from each cycle is enough.
    for (size_t j = (i / w) + (i % w) * h; j != i;
         j = (j / w) + (j % w) * h) {
      visited[j] = true;
    }
  }
}

So my question is, is there an algorithm that can result in the same cycles vector, but that won't require a vector like visited?

0 Answers
Related