sorting - Comb_sort doesn't work in Perl -
i wrote comb sort in perl. looks good, program doesn't work , compiler doesn't show errors. ask help. code is:
@tab = (1,3,5,22,2,12,1); $gap = scalar(@tab); $replace = 1; while ($gap>1 || $replace) { $gap = ($gap * 10) / 13; if ($gap == 0) { $gap = 1; } $replace = 0; ($i=0; $i+$gap < $n ; $i++) { if ($tab[$i]>$tab[$i+$gap]) { ($tab[$i], $tab[$i+$gap]) = ($tab[$i+$gap],$tab[$i]); $replace = 1; } } } print "sorted array: @tab";
the revised code uses $n
never sets it. if used use warnings;
, use strict;
, have known problem. directives, get:
$ perl comb.pl global symbol "$n" requires explicit package name @ comb.pl line 20. execution of comb.pl aborted due compilation errors. $
there 5 variables in code, including $n
, there's need my
appear 5 times.
with $n
set initial value of $gap
(aka scalar(@tab)
), code sorts data set ok, , mine.
#!/usr/bin/env perl use strict; use warnings; @tab = ( 19, 13, 2, 5, 3, 11, 17, 7 ); #my @tab = (1,3,5,22,2,12,1); $gap = scalar(@tab); $replace = 1; $n = $gap; print "unsorted array: @tab\n"; while ($gap>1 || $replace) { $gap = ($gap * 10) / 13; $gap = 1 if ($gap == 0); print "gap = $gap\n"; $replace = 0; (my $i=0; $i+$gap < $n; $i++) { if ($tab[$i]>$tab[$i+$gap]) { ($tab[$i], $tab[$i+$gap]) = ($tab[$i+$gap],$tab[$i]); $replace = 1; } } } print "sorted array: @tab\n";
sample run — data
unsorted array: 1 3 5 22 2 12 1 gap = 5.38461538461539 gap = 4.14201183431953 gap = 3.18616294947656 gap = 2.45089457652043 gap = 1.88530352040033 gap = 1.45023347723102 gap = 1.11556421325463 gap = 0.85812631788818 sorted array: 1 1 2 3 5 12 22
sample run — data
unsorted array: 19 13 2 5 3 11 17 7 gap = 6.15384615384615 gap = 4.73372781065089 gap = 3.64132908511607 gap = 2.80102237316621 gap = 2.15463259474323 gap = 1.65740968826403 gap = 1.27493052943387 gap = 0.980715791872205 sorted array: 2 3 5 7 11 13 17 19
if plan ask more questions perl on so, please make sure you've fixed obvious problems reported using use strict;
, use warnings;
— or, if can't, question should how fix specific warning or error you're getting.
please remember study how create mcve (minimal, complete, verifiable example) or sscce (short, self-contained, correct example) — 2 names , links same basic idea.
Comments
Post a Comment