Google
 
   
Login
Username:

Password:


Lost Password?

Register now!
Search
Main Menu
top books
Polls
What do you think about php-deluxe.net?
Excellent!
Cool
Hmm..not bad
What the hell is this?
encyclopedia
recommendation
compare webbrowser
Freenet DSL
Who's Online
12 user(s) are online (12 user(s) are browsing encyclopedia)

Members: 0
Guests: 12

more...
browser tip
Unix Befehle
manual of unix befehle
recommendation!
Sponsored
partner

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:

  • 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 of (A+B) arithmetic overflow, i.e., when the sum exceeds the maximum allowable number for a given number of bits.