Let's Learn it Together !

ِAn educational blog from FCIS'2011 students ..

Swapping variables is a very common operation used it tons of algorithms… like sorting. The most common and obvious technique is using a temporary variable to swap values between two variables:



void swap(int &i, int &j)

{

int temp = i;

i = j;



j = temp;

}






Instead of writing a separate function for each data type, you could write a MACRO or templatize the function.


Swapping without using a temporary variable is an age old trick and there are a few ways to do this. You could use the basic arithmetic operations like +, -, /, *.




void swap(int &i, int &j)

{

i = i + j;

j = i - j;

i = i - j;

}




The technique involves storing the sum of variables in one of them and then extracting it back by subtracting the other number. There are different variants to this technique… instead of starting by storing the sum, you could store the difference, product or the quotient. The last two could lead you to round-off and integer division errors. However all of them have one fundamental flaw. Its in line 3, and the issue is that this could lead to an overflow error.



This is another technique the gets you around these issues; the XOR Swapping Technique.




void swap(int &i, int &j)

{

i = i ^ j;

j = j ^ i;

i = i ^ j;

}




This is an elegant technique and should work well with any primitive data type and you could write a simple MACRO like



#define SWAP(i, j) (((i) ^= (j)), ((j) ^= (i)), ((i) ^= (j)))


Thanks to F.M.A.R. who sent me this article...


This is the pdf version of this article.

3 comments:

معلش يا دكتور يعنى ايه
MACRO
وايه فايدته ؟؟؟

doctor so why he uses this method and not the simplest swap ?

@5olio
shoof el link da
http://www.ebyte.it/library/codesnippets/WritingCppMacros.html

@Rehab
el solution el simple bysta5dem variable zyada 3an el 2 swaps el tanyeen :D, heya mesh far2a awe hena, bas lamma el projects teb2a kbeera w keda a3taqed en el 7agat de btefre2, en enty t7awly te3mely koll 7aga b a2al memory momkena

Post a Comment