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).

In reply to Re: [OT] Swapping buffers in place. by bitingduck
in thread [OT] Swapping buffers in place. by BrowserUk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.