Jump to content

Swap by addition and subtraction

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by 202.156.2.210 (talk) at 04:33, 27 December 2004 (Swap By Addition and Subtraction (Please help to refine this article! Thanks!)). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.
(diff) ← Previous revision | Latest revision (diff) | Newer revision → (diff)

Standard swapping algorithms require the use of a temporary storage area - standard intuitive algorithms to swap x and y involve:

  • copying  y aside to a temporary storage area
  • setting  y to be x
  • copying the temporary storage value back to x.

However, this algorithm requires only the mathematical operations of addition and subtraction. The algorithm follows (where A and B are the values stored in the variables X and Y respectively): X has A, Y has B. Step 1: Add X and Y and store in X Now X has A + B, Y has B. Step 2: Subtract Y from X and store in Y Now X has A + B, Y has A. Step 3: Subtract Y from X and store in X Now X has B, Y has A. Swap done.

The algorithm looks much simpler when it is written in pseudocode.

X := X + Y
Y := X - Y
X := X - Y

Limitation: Due to the addition operation in the first step, this swap algorithm would fail for the case where (A+B) exceed the maximum allowable number for a given number of bits.