sorting - How can I get this basic Perl sub program that sorts to work properly? -
i brand new perl. can me out , give me tip or solution on how sorting sub program work. know has how arrays passed sub programs. searched online , did not find answer satisfied with... suggestions helpful s.o. users give me too. have program print sorted array in main sub program. currently, printing elements of array @a in original order. want sub program modify array when print array in sorted order. suggestions appreciated. of course, want see simplest way fix this.
sub sort { @array = @_; $i; $j; $imin; ( $i = 0; $i < @_ - 1; $i++ ) { $imin = $i; ( $j = $i + 1; $j < @_; $j++ ) { if ( $array[$j] < $array[$imin] ) { $imin = $j; } } if ( $imin != $i ) { $temp = $array[$i]; $array[$i] = $array[$imin]; $array[$imin] = $temp; } } }
then call main sub program:
sub main { @a = (-23,3,234,-45,0,32,12,54,-10000,1); &sort(@a); $i; ( $i = 0; $i < @a; $i++ ) { print "$a[$i]\n"; } } main;
when sub following assignment my @array = @_
, creating copy of passed contents. therefore modifications values of @array
not effect @a
outside subroutine.
following clarification personal learning exercise, there 2 solutions.
1) can return
sorted array , assign original variable
sub mysort { @array = @_; ... return @array; } @a = mysort(@a)
2) or can pass reference array, , work on reference:
sub mysort { $arrayref = shift; ... } mysort(\@a)
also, it's idea not use sub named sort
since that's that's builtin function. duplicating code using perl's sort:
@a = sort {$a <=> $b} @a;
also, loops inside sub should rewritten utilize last index of @array
, written $#array
, , range operator ..
useful incrementors :
for ( $j = $i + 1; $j <= $#array; $j++ ) { # or simpler: $j ($i+1 .. $#array) {
and finally, because you're new, should pass on scripts should start use strict;
, use warnings;
. reasons why: why use strict , warnings?
Comments
Post a Comment