Swap by addition and subtraction |
Standard swapping Algorithms require the use of a temporary storage area - standard intuitive algorithms to swap x and y involve:
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 of (A+B) arithmetic overflow, i.e., when the sum exceeds the maximum allowable number for a given number of bits.|
|