Given a permutation P = randperm(N) for $N\approx 10^6$.
How to compute the number of cycles of the permutation represented by P in MATLAB efficiently?
Given a permutation P = randperm(N) for $N\approx 10^6$.
How to compute the number of cycles of the permutation represented by P in MATLAB efficiently?
Copyright © 2021 JogjaFile Inc.
Brute force should do it pretty fast. Make a table with $N$ entries, all zeroes.
The "until no more nonzero entries" can be sped up by searching the table upwards starting from the current value of $k0$.
If you store your permutation in a sparse matrix or hashtable, you should be able to do this all in nearly O(N) time.