What are the various ways to swap 2 variables
I know about these. Is there any other ways as well? And which one is better?
- Using temporary Variables
- Using some Arithmetic operation
- Using bitwise XOR operation
I b开发者_StackOverflow中文版elieve the best approach is the XOR implementation. Any suggestions?
Anything that doesnt use temporary variable/register is guaranteed not to work always. Hence NOT advised to use it.
Bitwise XOR swap doesnt work on same variable.(http://en.wikipedia.org/wiki/XOR_swap_algorithm#Reasons_for_avoidance_in_practice)
'Arithmetics without temp variable swap' will have overflow issues.
Also note that if you do a simple swap using temporary, compiler is smart enough to convert it to assembly without using temp variable. If you try to over-smart it, then
- Your code will end equal or slower AND
- Your code will be less readable for sure.
These two binary operations #
and @
are inverses of each other, the following algo will also swap the values of a and b:
a = a # b
b = a @ b
a = a @ b
Hope this helps.
Also possible is tuple unpacking:
Python 2.7.1 (r271:86882M, Nov 30 2010, 10:35:34)
[GCC 4.2.1 (Apple Inc. build 5664)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> a = 4
>>> b = 23
>>> a, b = b, a
>>> a
23
>>> b
4
>>>
Depending on your language and the complexity of your options, an option d) is to swap internal pointers. For example, if you have your own string object (in practice you'd use the standard library of your favorite language), it might contain a integer length and a pointer to the memory to store the string. When swapping instances of the string object you'd swap only the length and the pointer to the data, not the data itself.
I think using the temporary variable solution is much better because:
- It is easy to read
- Can be used between multiple types
- Results is no arithmetic/logical operation
- No overflow related problem
- One extra memory space is not a huge overhead
Checkout these links:
- http://c-faq.com/misc/swapnotemp.html
- http://c-faq.com/expr/xorswapexpr.html
精彩评论