1: # for those times when Perl's built-in sort is just too fast
   2: 
   3: use strict;
   4: 
   5: my @data = qw(7 6 5 4 3 2 1 0) ;
   6: 
   7: rpsort(\@data);
   8: print "$_\t" foreach (@data);
   9: 
  10: exit;
  11: 
  12: # a random permutation sort
  13: # ref. Perl Cookbook recipe 4.17 for the shuffle
  14: 
  15: sub rpsort {
  16: 	my $list = shift;
  17: 	my ($k,$j);
  18: 
  19: try_again:
  20: 	for ($j = @$list; --$j; ) {
  21: 		$k = int rand($j+1);
  22: 		next if ($j == $k);
  23: 		@$list[$j, $k] = @$list[$k, $j];
  24: 	}
  25: 
  26: 	for ($j = 0 ; $j < (@$list -1); $j++) {
  27: 		goto try_again if (@$list[$j] > @$list[$j+1]);
  28: 	}
  29: }

Replies are listed 'Best First'.
Re: Random Permutation Sort
by arhuman (Vicar) on Jul 15, 2001 at 13:02 UTC
    Even If I ++ you for your contribution,
    I'd like however to suggest you (and others) to re-use existing monastery resources,
    and PROMOTE their use...

    using Super Search : with 'shuffle' or 'fisher yates' as keywords would give several posts,
    with this Fisher-Yates algorithm.
    You might even find something in the FAQ (How do I shuffle an array randomly?)

    Hope this won't prevent you to go on contributing ;-)

    "Only Bad Coders Code Badly In Perl" (OBC2BIP)