The while (not $sorted) checks whether there was a swap in the previous cycle. If not, all neighboring pairs in the list satisfy the condition $list[$i]<=$list[$i+1], i.e. the list is sorted. Another common optimization of bubblesort would be to only sort the part of the list that isn't sorted yet. (Hope you only take this as an exercise, sort would do this quicker and easier)
sub bubbleSort { my @list = @_; my $cutoff; my $last_changed = @list; while ( $last_changed ) { $cutoff = $last_changed; $last_changed = 0; for my $current ( 1 .. $cutoff ) { my $previous = $current - 1; if ( $list[$current] < $list[$previous] ) { ($list[$current], $list[$previous]) = ($list[$previous +], $list[$current]); $last_changed = $previous; } } } return @list; }
And, please, use <code> tags to enclose your code next time
In reply to Re: while condition bubbleSort
by pjotrik
in thread while condition bubbleSort
by santosh_br
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |