initially, x points to 1, y points to a:1 2 3 4 5 6 a b c
We want to move a b c all the way to the left,so we swap numbers and letters:x y 1 2 3 4 5 6 a b c
Now the rightmost elements are scrambled. Note that y at this stage points to the element one off the right end of the array. We restore its position:x y a b c 4 5 6 1 2 3
Now we basically have a smaller array 4 5 6 1 2 3 and we want to swap 4 5 6 and 1 2 3. Hence, recursion. But it's a tail call, aka 'while loop in disguise', so:$y = $offset_y if $y == @$ary; x y a b c 4 5 6 1 2 3
Same thing... I think :)sub do_swaps { my ( $ary, $offset_x, $offset_y, $swaps ) = @_; my ( $x, $y ) = ( $offset_x, $offset_y ); while ( $offset_y != @$ary ) { for ( $offset_x .. ( $offset_y - 1 ) ) { $y = $offset_y if $y == @$ary; my $temp = $ary->[$x]; $ary->[$x] = $ary->[$y]; $ary->[$y] = $temp; $x += 1; $y += 1; $swaps += 1; } ( $offset_x, $offset_y ) = ( $x, $y ); } return $swaps; }
In reply to Re^3: [OT] Swapping buffers in place.
by Anonymous Monk
in thread [OT] Swapping buffers in place.
by BrowserUk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |