#!/usr/bin/perl
use strict;
use warnings;
## 生成100以内的10000个随机数
my @arr;
for(my $i=0;$i<10000;$i++){
my $num=int(rand(100));
push @arr,$num;
}
## 不同方法排序,并记录时间
my $time1 = time;
my @sort1 = &sort_selected(@arr);
my $time2 = time;
my @sort2 = &sort_inserted(@arr);
my $time3 = time;
for(my $i=0;$i<1000000;$i++){
my $num=int(rand(100));
push @arr,$num;
}
my @sort3 = &sort_merged(@arr);
my $time4 = time;
my @sort4 = sort {$a<=>$b} @arr;
my $time5 = time;
my $time_se=$time2-$time1;
my $time_in=$time3-$time2;
my $time_me=$time4-$time3;
my $time_systerm = $time5 - $time4;
## 检验排序结果是否正确
my $result1 = &sort_test(@sort1);
my $result2 = &sort_test(@sort2);
my $result3 = &sort_test(@sort3);
## 进行运行时间及结果正确性的输出
print "sort_selected: $time_se\t$result1\n";
print "sort_insertted: $time_in\t$result2\n";
print "sort_merged: $time_me\t$result3\n";
print "time_systerm: $time_systerm\n";
## 选择排序,核心思想:先将最小数字找出,放在第一位,然后将剩余元素中最小数字找出,放在第二位,依次排完
sub sort_selected{
my @unsort = @_;
foreach my $i (0..$#unsort){
my $min = $unsort[$i];
my $k =$i;
foreach my $j($i+1..$#unsort){
if ($min>$unsort[$j]){
$min = $unsort[$j];
$k = $j;
}
}
$unsort[$k] = $unsort[$i];
$unsort[$i] = $min;
}
return @unsort;
}
## 内插排序,核心思想:从第二个元素开始,看它适合插在前面的那个位置,类似于打扑克牌时放牌的做法
sub sort_inserted{
my @unsort = @_;
foreach my $i ( 1..$#unsort){
my $tmp = $unsort[$i];
my $j= $i-1;
for ($j=$j; $j>=0; $j--) {
if ($tmp < $unsort[$j]) {
$unsort[$j+1] = $unsort[$j];
}
else{
last;
}
}
$unsort[$j+1]=$tmp;
}
return @unsort;
}
## 归并排序,实现起来有点绕,思想相对比较简单,就是先将数组从中间一分为2,再迭代的每个数组一分为2,直至最小单元是一个元素;然后反向的merge即可,合并相邻的两个小数组;内存会多点,但是计算会降低;我在处理一分为二迭代的时候出了点问题,使用的1>2>4>8>16合并的策略
sub sort_merged{
my @raw = @_;
my $k=2;
for (my $i=0; $i<= $#raw-1; $i=$i+$k){
if ($raw[$i] > $raw[$i+1]){
my $tmp = $raw[$i];
$raw[$i] = $raw[$i+1];
$raw[$i+1] =$tmp;
}
}
for ($k=2;$k<$#raw;$k=$k*2){
for (my $i=0; $i<= ($#raw-1); $i = $i+ 2*$k){
my $end1 = $i+$k-1 < $#raw? $i+$k-1 : $#raw;
my $end2 = $i+$k*2-1 < $#raw? $i+2*$k-1 : $#raw;
if ($end1 == $#raw){next;}
my @sort1=@raw[$i..$end1];
my $start2=$i+$k;
my @sort2=@raw[$start2..$end2];
my @sort;
my $j=0;
for (my $m=0;$m<=$#sort1;$m=$m+0){
if ($sort1[$m] < $sort2[$j]){
push @sort,$sort1[$m];
$m++;
}
elsif ($sort1[$m] > $sort2[$j]){
push @sort,$sort2[$j];
$j++;
}
elsif ($sort1[$m] == $sort2[$j]){
push @sort,$sort1[$m];
push @sort,$sort2[$j];
$m++;
$j++;
}
if($j > $#sort2){
foreach my $lm ($m..$#sort1) {
push @sort, $sort1[$lm];
}
last;
}
}
if ($j <= $#sort2){
foreach my $lm ($j..$#sort2) {
push @sort, $sort2[$lm];
}
}
@raw[$i..$end2]=@sort;
}
}
return(@raw);
}
## 验证排序顺序是否正确
sub sort_test {
my (@sort) = @_;
foreach my $i (0..$#sort-1){
if ($sort[$i+1] < $sort[$i]){
return ("err");
}
}
return ("sorted");
}
# 100内一万数字
sort_selected: 2 sorted
sort_insertted: 3 sorted
sort_merged: 0 sorted
time_systerm: 0
# 前两个100内一万数字,后两个100内100万数字
sort_selected: 2 sorted
sort_insertted: 4 sorted
sort_merged: 8 sorted
time_systerm: 0
# 归并排序确实是快几十倍,但是跟内置的排序差距还是很大的
# 看来相对于内置的排序方式还是有很大的进步空间呀
网友评论