第一次发博文,希望各位老师多多指导!
本人最近在学Perl语言,并试图用Perl实现计算机的一些算法,现用Perl实现了归并排序,有什么不好的地方,希望大家能帮忙指出来。
#!usr/bin/perl -w
if(!open MYFILE,'/Users/Sky/Desktop/data.txt')#Open file handle-MYFILE to connect source file which need to sort;
{
print "Cannot open the source file!";
}
$t=0;
foreach(<MYFILE>)#output the data of source file to array @a;
{
$a[$t]=$_;
$t++;
}
close(MYFILE);
$a=@a;#the number of @a;
print &MergeSort(0,$a-1,@a);#output @a which has been sorted;
sub MergeSort#split the array into 2 parts;
{
my($f,$r,@array)=@_;
my $mi;
if($f<$r)
{
$mi=int(($f+$r)/2);
@array=&MergeSort($f,$mi,@array);#recur itself;
@array=&MergeSort($mi+1,$r,@array);
@array=&Merge($f,$mi,$r,@array);#call merge sub_function;
}
return @array;
}
sub Merge#merge the 2 parts into the only array @arra;
{
my($f,$mi,$r,@arra)=@_;
$i=$f;
$j=$mi+1;
$k=0;
my @arr=();#for the sorted sequence;
while($i<=$mi && $j<=$r)
{
if($arra[$i]<=$arra[$j])
{
$arr[$k++]=$arra[$i++];
}else
{
$arr[$k++]=$arra[$j++];
}
}
while($i<=$mi)
{
$arr[$k++]=$arra[$i++];
}
while($j<=$r)
{
$arr[$k++]=$arra[$j++];
}
$i=$f;
foreach(@arr)
{
$arra[$i++]=$_;
}
return @arra;
}
https://m.sciencenet.cn/blog-752323-630654.html
下一篇:
Use MergeSort to Count Inversions by Perl