Ahmed Ghoneim
Ahmed Ghoneim

Reputation: 7067

Swapping Integers Efficiency

Simply,

X = Integer
Y = Another Integer

Z ( If used ,Integer Temp )

What's the most efficient method ?

Method I :

Z = X
X = Y
Y = Z

Method II :

X ^= Y
Y ^= X
X ^= Y

Edit I [ Assembly View ]

Method I :

MOV  
MOV  
MOV

Method II :

TEST ( AND )  
JZ  
XOR  
XOR  
XOR

Notes :

Upvotes: 1

Views: 586

Answers (2)

abhi120
abhi120

Reputation: 278

Try this way of swapping numbers

int a,b;

a=a+b-(b=a);

Upvotes: 0

Eric J.
Eric J.

Reputation: 150108

In most cases, using a temporary variable (usually a register at assembly level) is the best choice, and the one that a compiler will tend to generate.

In most practical scenarios, the trivial swap algorithm using a temporary register is more efficient. Limited situations in which XOR swapping may be practical include: On a processor where the instruction set encoding permits the XOR swap to be encoded in a smaller number of bytes; In a region with high register pressure, it may allow the register allocator to avoid spilling a register. In microcontrollers where available RAM is very limited. Because these situations are rare, most optimizing compilers do not generate XOR swap code.

http://en.wikipedia.org/wiki/XOR_swap_algorithm

Also, your XOR Swap implementation fails if the same variable is passed as both arguments. A correct implementation (from the same link) would be:

void xorSwap (int *x, int *y) {
     if (x != y) {
         *x ^= *y;
         *y ^= *x;
         *x ^= *y;
     }
 }

Note that the code does not swap the integers passed immediately, but first checks if their addresses are distinct. This is because, if the addresses are equal, the algorithm will fold to a triple *x ^= *x resulting in zero.

Upvotes: 3

Related Questions