perl语言的几种排序?比如,快速排序法,插入排序法,归并排序,选择排序等等,写几个都可以 50
1个回答
展开全部
sub qsort {
my @arr = @_;
if ($#arr <= 1) {
if ($#arr == 1 && $arr[1] < $arr[0]) {
@arr[1,0] = @arr[0,1];
}
return @arr;
}
my $p = $arr[int(rand($#arr + 1))];
my (@s, @e, @b);
foreach my $e(@arr) {
if ($e < $p) {push @s, $e;}
elsif ($e > $p) {push @b, $e;}
else {push @e, $e;}
}
my @res;
if ($#s >= 0) {push @res, qsort(@s);}
if ($#e >= 0) {push @res, @e;}
if ($#b >= 0) {push @res, qsort(@b);}
return @res;
}
sub merge_sort {
my @arr = @_;
if ($#arr <= 1) {
if ($#arr == 1 && $arr[1] < $arr[0]) {
@arr[1,0] = @arr[0,1];
}
return @arr;
}
my $m = $#arr >> 1;
my @l = merge_sort(@arr[0..$m]);
return @l if ($m == $#arr);
my @r = merge_sort(@arr[$m+1 .. $#arr]);
my @m;
my ($l, $r) = (0, 0);
while ($l <= $#l && $r <= $#r) {
if ($l[$l] < $r[$r]) {push @m, $l[$l++];}
else {push @m, $r[$r++];}
}
push @m, @l[$l .. $#l] if ($l <= $#l);
push @m, @r[$r .. $#r] if ($r <= $#r);
return @m;
}
my @arr = map{int rand(100)}0..20;
my @res = qsort(@arr);
print "@res\n";
@arr = map{int rand(100)}0..20;
@res = merge_sort(@arr);
print "@res\n";
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询