问题
Where can I find what algorithm Matlab's randperm function uses? Is it Fisher-yates (Knuth) shuffling algorithm or something else?
回答1:
For MATLAB releases as early as R2009b, randperm is implemented as follows:
function p = randperm(n)
[ignore, p] = sort(rand(1, n));
You can see it for yourself by typing:
type randperm
Basically randperm generates n numbers and sorts them, returning the resulting array of ordered indices p as the random permutation. The time complexity for this is O(nlogn) at best, worse than Fisher-and-Yates' shuffle, which runs at O(n).
EDIT: Dennis points out that in later releases randperm runs at O(n) time, so obviously it's improved. However, it's a built-in function so it is impossible to see its implementation.
来源:https://stackoverflow.com/questions/16418353/what-algorithm-is-randperm-based-on