in reply to Fisher-Yates theory

The following is straight out of the FAQ. Use perldoc -q shuffle to read the whole entry.

sub fisher_yates_shuffle { my $deck = shift; # $deck is a reference to an array my $i = @$deck; while ($i--) { my $j = int rand ($i+1); @$deck[$i,$j] = @$deck[$j,$i]; } }

Update: Uh. Gee... you did ask for the theory not the code. Sorry. What is there to tell you? It's O(N) for obvious reasons and it works on the data in place so memory usage is minimal. It's a very straightforward algorithm.

-sauoq
"My two cents aren't worth a dime.";

Replies are listed 'Best First'.
Re: Fisher-Yates theory
by Abigail-II (Bishop) on Jul 24, 2003 at 08:13 UTC
    Well, there's more to an algorithm than its run-time complexity. You also need to prove the algorithm is correct. That is in this case show that the resulting array is a permutation of the original one (fairly trivial), and that each permutation has an equal chance of being selected (a bit more work, but still not to hard, if you can assume your random generator produces real random numbers).

    For details, see the Knuth reference I made in another post in this thread.

    Abigail