为了简单起见,我试图让这个堆以格式化的树形式打印。它很接近,但我知道我缺少了东西,但我无法绕过这个模块。我知道有树::简单,我认为只是树?但是我无法找到关于如何实际使用列表或数组的任何教程。堆排序是正确的,因为它在发布树之后对列表进行排序但是我无法确定如何正确地绘制树,然后再次输出从来就不是我在任何语言上的强项。我认为它没有抓取文件中的数据?至少这是我的想法,但我没有足够的信心确定。到目前为止,这是我的代码。
#!/usr/bin/perl
use 5.006;
use strict;
use warnings;
use Tree::DAG_Node;
process_data(read_file('data.txt'));
process_data((3,1,4,1,5,9,2,6,5,3,6));
sub read_file{
my($filename)=@_;
my @data=();
my @words;
open(my $fh, "<", $filename)
or die "Could not open file: $!\n";
while(<$fh>){
chomp;
@words = split(' ');
foreach my $word(@words) {
push @data, $word;
}
}
close $fh;
return @data;
}
sub heap_sort {
my ($a) = @_;
my $n = @$a;
for (my $i = ($n - 2) / 2; $i >= 0; $i--) {
down_heap($a, $n, $i);
}
for (my $i = 0; $i < $n; $i++) {
my $t = $a->[$n - $i - 1];
$a->[$n - $i - 1] = $a->[0];
$a->[0] = $t;
down_heap($a, $n - $i - 1, 0);
}
}
sub down_heap {
my ($a, $n, $i) = @_;
while (1) {
my $j = max($a, $n, $i, 2 * $i + 1, 2 * $i + 2);
last if $j == $i;
my $t = $a->[$i];
$a->[$i] = $a->[$j];
$a->[$j] = $t;
$i = $j;
}
sub max {
my ($a, $n, $i, $j, $k) = @_;
my $m = $i;
$m = $j if $j < $n && $a->[$j] > $a->[$m];
$m = $k if $k < $n && $a->[$k] > $a->[$m];
return $m;
}
}
sub draw_tree{
my(@data)=@_;
my $root = Tree::DAG_Node->new;
$root->name($_[0]);
$root->new_daughter->name($_) for ('1'..'10');
my @names = @data;
my $count =0;
for my $n ($root->daughters) {
for (split //, $names[$count++]) {
$n->new_daughter->name($_)
}
}
print map "$_\n", @{$root->draw_ascii_tree};
}
sub process_data{
my(@data)=@_;
my @a = @data;
print "@a\n";
print "\n";
heap_sort(\@a);
print "\n";
print "@a\n";
print "\n";
draw_tree(@a);
}
这是我到目前为止的输出。
10,4,5,2,1,7
Use of uninitialized value in split at HEAPSORTtree.pl line 77.
Use of uninitialized value in split at HEAPSORTtree.pl line 77.
Use of uninitialized value in split at HEAPSORTtree.pl line 77.
Use of uninitialized value in split at HEAPSORTtree.pl line 77.
Use of uninitialized value in split at HEAPSORTtree.pl line 77.
Use of uninitialized value in split at HEAPSORTtree.pl line 77.
Use of uninitialized value in split at HEAPSORTtree.pl line 77.
Use of uninitialized value in split at HEAPSORTtree.pl line 77.
Use of uninitialized value in split at HEAPSORTtree.pl line 77.
|
<10,4,5,2,1,7>
/---------------------------------------+--
-+---+---+---+---+---+---+---\
| |
| | | | | | | |
<1> <2>
<3> <4> <5> <6> <7> <8> <9> <10>
/-----------------+-----------------+---+---+---+---+---+---+---+---+---\
| | | | | | | | | | | |
<1> <Tree::DAG_Node=HASH(0x4b32dc)> <,> <4> <,> <5> <,> <2> <,> <1> <,> <7>
10,4,5,2,1,7
3 1 4 1 5 9 2 6 5 3 6
|
<1>
/---+---+---+---+---+---+---+---+---\
| | | | | | | | | |
<1> <2> <3> <4> <5> <6> <7> <8> <9> <10>
| | | | | | | | | |
<1> <1> <2> <3> <3> <4> <5> <5> <6> <9>
1 1 2 3 3 4 5 5 6 9 6
Press any key to continue . . .
我想要的输出类似于这个
|
<root>
/-------+-------+-------\
| | | |
<1> <d> <e> <f>
/---+---\ |
| | | <3>
<a> <b> <c> /---+---\
| | |
<g> <h> <i>