#!/usr/bin/perl
use warnings;
sub stupidSort
{
my $flag=1;
while($flag)
{
for(my $i=0; $i<@_-1; $i++)
{
if($_[$i]>$_[$i+1])
{
@_[$i, $i+1]=@_[$i+1, $i];
last;
}
}
$flag=0;
}
return @_;
}
print "$_\n" for stupidSort(@ARGV);
#!/usr/bin/perl
use warnings;
sub bubbleSort
{
my $right=$#_;
while($right)
{
for(my $i=0; $i<$right; $i++)
{
@_[$i, $i+1]=@_[$i+1, $i] if $_[$i]>$_[$i+1];
}
$right--;
}
return @_;
}
print "$_\n" for bubbleSort(@ARGV);
#!/usr/bin/perl
use warnings;
sub bubbleEnhancedSort
{
my $right=$#_;
while($right)
{
my $lastSwap=0;
for(my $i=0; $i<$right; $i++)
{
if($_[$i]>$_[$i+1])
{
@_[$i, $i+1]=@_[$i+1, $i];
$lastSwap=$i;
}
}
$right=$lastSwap;
}
return @_;
}
print "$_\n" for bubbleEnhancedSort(@ARGV);
#!/usr/bin/perl
use warnings;
sub shakerSort
{
my $left=0;
my $right=$#_;
while($left<$right)
{
my $lastSwap;
for(my $i=$lastSwap=$left; $i<$right; $i++)
{
if($_[$i]>$_[$i+1])
{
@_[$i, $i+1]=@_[$i+1, $i];
$lastSwap=$i;
}
}
$right=$lastSwap;
for(my $i=$lastSwap=$right; $i>$left; $i--)
{
if($_[$i]<$_[$i-1])
{
@_[$i, $i-1]=@_[$i-1, $i];
$lastSwap=$i;
}
}
$left=$lastSwap;
}
return @_;
}
print "$_\n" for shakerSort(@ARGV);
#!/usr/bin/perl
use warnings;
sub insertionSort
{
for my $i(0..$#_)
{
for my $j(0..$i-1)
{
if($_[$j]>$_[$i])
{
while($j<$i)
{
@_[$i, $i-1]=@_[$i-1, $i];
$i--;
}
last;
}
}
}
return @_;
}
print "$_\n" for insertionSort(@ARGV);
#!/usr/bin/perl
use warnings;
sub selectionSort
{
for my $i(0..$#_-1)
{
my $k=$i;
for my $j($i+1..$#_)
{
$k=$j if $_[$k]>$_[$j];
}
@_[$i, $k]=@_[$k, $i];
}
return @_;
}
print "$_\n" for selectionSort(@ARGV);
#!/usr/bin/perl
use warnings;
sub treeAddElement
{
my $tree=shift;
my $n=shift;
if(@$tree)
{
treeAddElement($tree->[$n<$tree->[0]? 1: 2], $n);
}
else
{
@$tree=($n, [], []);
}
}
sub treeToArray
{
my $tree=shift;
return () unless @$tree;
return (treeToArray($tree->[1]), $tree->[0], treeToArray($tree->[2]));
}
sub treeSort
{
my $tree=[];
treeAddElement($tree, $_) for @_;
return treeToArray($tree);
}
print "$_\n" for treeSort(@ARGV);
#!/usr/bin/perl
use warnings;
sub recursiveSort
{
return () unless @_;
my $key=shift;
my @left;
my @right;
for(@_)
{
if($_<$key) { push @left, $_; }
else { push @right, $_; }
}
return (recursiveSort(@left), $key, recursiveSort(@right));
}
print "$_\n" for recursiveSort(@ARGV);
#!/usr/bin/perl
use warnings;
print "$_\n" for sort { $a<=>$b } @ARGV;
#!/usr/bin/perl
use warnings;
sub shuffle
{
my %randoms;
for(@_)
{
my $rand;
do
{
$rand=rand;
}
while(exists $randoms{$rand});
$randoms{$rand}=$_;
}
return @randoms{sort { $a<=>$b } keys %randoms};
}
print "$_\n" for shuffle(@ARGV);
Алгоритм Фишера — Йетса — Дурштенфельда
#!/usr/bin/perl
use warnings;
sub fisherShuffle
{
for(my $i=$#_; $i>0; $i--)
{
my $j=int(rand($i+1));
@_[$i, $j]=@_[$j, $i];
}
return @_;
}
print "$_\n" for fisherShuffle(@ARGV);