Thursday, October 27, 2011

Swap 2 Variables

This problem can be seen everywhere, and almost every people knows the solution. In this post, I'm going to summarize 3 functions for swap.

Function 1: naiveSwap

Function 2: xorSwap

Function 3: addSwap

Summary:
naiveSwapxorSwapaddSwap
extra variableneednot neednot need
check \(x \ne y\) (address)not needneedneed
readabilitygoodnot goodnot good
overflowno problemno problempotential problem
aliasingfinecomplicatedcomplicated
execution modelinstruction pipelinestrictly sequentialstrictly sequential


Situations for XOR use in practice:
  • 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 don't generate XOR swap code.

Because of the problem of overflow, the add-swap approach is used less often.


References:
Wikipedia item: XOR swap algorithm

No comments:

Post a Comment