Your skill will accomplishwhat the force of many cannot PerlMonks

### Re: Sorting Arrays Without using SORT function

by Fletch (Chancellor)
 on Feb 15, 2011 at 17:24 UTC ( #888321=note: print w/replies, xml ) Need Help??

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

If PC isn't allowed to use the sort function, then List::Util is probably even more forbidden.

```use strict;
use warnings;

my @array = qw(h o m e w o r k);
while (not isSorted(@array))
{
print +(join ", ", @array) . "\r";
my (\$x, \$y) = (rand(scalar @array), rand(scalar @array));
(\$array[\$x], \$array[\$y]) = (\$array[\$y], \$array[\$x]);
}
print "\nSort complete!\n";
print join ", ", @array;

sub isSorted
{
my \$x = shift;
while (my \$y = shift)
{
return 0 unless (\$x cmp \$y) < 1;
\$x = \$y;
}
return 1;
}

Create A New User
Node Status?
node history
Node Type: note [id://888321]
help
Chatterbox?
 shmem sees a creepy one choroba is at a security training [choroba]: the presenter was able to fix an expired certificate in their demo application, but now he's getting java stacktrace instead of the pages [virtualsue]: Thank you, Discipulus. I must now go write some code. :-)

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (8)
As of 2018-04-24 11:13 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
My travels bear the most uncanny semblance to ...

Results (85 votes). Check out past polls.

Notices?