in reply to Re: Re: Re: bubble sort in perl
in thread bubble sort in perl
enough about that. your code is broken. it only performs one pass through the data, so it will only sort one element. try something like: Update: i need to eat breakfast before i post any more... and i prefer the sort all in one sub, so here's mine (lifted from mastering algorithms, if i recall correctly:)
which iterates through the array backwards (the sorted data gathers on the tail end) and swaps elements until they're ordered.sub bubble { my @array = @{ $_[0] }; for( my $i = $#array; $i; $i-- ) { for( my $j = 1; $j <= $i; $j++ ) { @array[$j, $j-1] = @array[$j-1, $j] if( $array[$j-1] > $array[$j] ); } } return \@array; } my $aRef = [ 2, 4, 3, 5, 1 ]; my $aSortedRef = bubble( $aRef ); print "@{$aRef}$/"; print "@{$aSortedRef}$/";
also, your code sorts data in-place. i modified it to sort to a new array, as it's my preference.
~Particle ;Þ
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Re:(4) bubble sort in perl
by RMGir (Prior) on Mar 24, 2002 at 14:37 UTC |