Here are 3 simple examples which is illustrating her algorithm basic skills(BTW, she is a math talented person i ever met during college)
Insertion Sorting:
@arry1 = (12,32,3,25,67,24,56);
@arry2 = shift @arry1;
$j=$#arry2;
foreach $arry (@arry1){
if ($arry2[$j]<= $arry) {
push @arry2, $arry;
}
elsif ($j==0 ) {
unshift @arry2, $arry;
}
else {
foreach (reverse(@arry2)){
if ($_ > $arry){
$j-=1;
}
}
if ($j >=0){
$i = $j+1;
@arry2= (@arry2[0..$j], $arry, @arry2[$i..$#arry2]);
}
else {
unshift @arry2, $arry;
}
}
$j=$#arry2;
}
foreach (@arry2){
print "$_ ";
}
Quick Sorting: @arry1=(12,32,3,25,67,24,56);
$i=0;
$j=$#arry1;
&quick_sorting($i,$j);
sub quick_sorting {
my($m,$n)= @_;
while ($m <$n){
if ($arry1[$m]<= $arry1[$n]) {
$n-=1;
}
else {
($arry1[$m], $arry1[$n]) = ($arry1[$n], $arry1[$m]);
$m+=1;
}
}
if ($m - $_[0]> 1) {
&quick_sorting($_[0], $m-1);
}
if ($_[1] -$n > 1){
&quick_sorting($n+1, $_[1]);
}
}
foreach $arry (@arry1){
print "$arry\n";
}
Bubble Sorting:
@arry1 = (12,32,3,25,67,24,56);
$i=0;
$j=$#arry1;
for ( ; $j >=0; $j-=1){
for ($i=0; $i<$j; $i+=1 ){
if ($arry1[$i]-$arry1[$i+1] gt 0) {
($arry1[$i], $arry1[$i+1])=($arry1[$i+1], $arry1[$i]);
}
}
}
foreach $arry (@arry1){
print "$arry\n";
}
No comments:
Post a Comment