http://qs321.pair.com?node_id=1118227


in reply to [OT] Swapping buffers in place.

Do you know a priori when the second half is shorter than the first? The obvious thing to me is to have a third buffer equal in size to the difference between the two where you store the part that you're about to overwrite.

The clever way that struck me while trying to get around that is to reverse the whole thing, then reverse each of the sub-buffers. It takes more time but it does it in place.

edit: other than the triple reverse, I can't do it in place (i.e. without a third buffer equal to the difference) without putting in a bunch of rotations to get the ends of the longer buffer in the right place:

first, swap the ends of the longer one so you won't overwrite the trailing elements of the long one:

[X0 X1 X2 X3 X4 X5 X6 X7 X8 X9 Y0 Y1 Y2 Y3 Y4 Y5 Y6 Y7]

becomes

[X8 X9 X2 X3 X4 X5 X6 X7 X0 X1 Y0 Y1 Y2 Y3 Y4 Y5 Y6 Y7]

then to a straight swap

[Y0 Y1 Y2 Y3 Y4 Y5 Y6 Y7 X0 X1 X8 X9 X2 X3 X4 X5 X6 X7]

then you're stuck rotating the trailing elements of the longer one back into place

[Y0 Y1 Y2 Y3 Y4 Y5 Y6 Y7 X0 X1 X9 X2 X3 X4 X5 X6 X7 X8] [Y0 Y1 Y2 Y3 Y4 Y5 Y6 Y7 X0 X1 X2 X3 X4 X5 X6 X7 X8 X9]
which I think usually takes more time than the triple reverse (which really is only two passes through the whole thing).