in reply to Sorting Arrays Without using SORT function
Sure, but runtime depends on your luck.
#!/usr/bin/env perl use strict; use warnings; use List::Util qw( shuffle reduce ); my @list = qw( f a d e z x c b ); sub in_order { my $state = 1; our( $a, $b ); my $ordered = reduce { if( $state and $b lt $a ) { $state = undef; } + $b } @_; return $state; } my $shuffles = 0; my @ordered = @list; my %memory; until ( in_order( @ordered ) ) { $memory{ join("\0",@ordered) } = 1; while( 1 ) { @ordered = shuffle( @list ); $shuffles++; last unless $memory{ join("\0",@ordered) }; } } print "took $shuffles shuffles to get\n\t", join( "\n\t", @ordered ), +"\n"; exit 0; __END__
The cake is a lie.
The cake is a lie.
The cake is a lie.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Sorting Arrays Without using SORT function
by SuicideJunkie (Vicar) on Feb 15, 2011 at 17:53 UTC |