Thursday, November 30, 2006

Swapping two integer values in C# [Interview Question]

Offlate, many of my friends where talking about this problem. It seems they ask this question frequently in Microsoft Interviews :) I remember asking this question to freshers in 2005!

Just thought I would refresh my knowledge also on this :) So here are few samples which I tried for your reference.

Method 1: Using intermediate temp variable

int intNumOne = 1, intNumTwo = 2;
int intTempVariable;

//Swapping of numbers starts here
intTempVariable = intNumOne;
intNumOne = intNumTwo;
intNumTwo = intTempVariable;

Response.Write("Value of First Variable :: " + intNumOne.ToString() + "<br>");
Response.Write("Value of Second Variable :: " + intNumTwo.ToString() + "<br>");

Method 2: Without using Temp Variable and by using 8th standard Mathematics :)

int intNumOne = 11, intNumTwo = 22;

//Swapping of numbers starts here
intNumOne = intNumOne + intNumTwo;
intNumTwo = intNumOne - intNumTwo;
intNumOne = intNumOne - intNumTwo;

Response.Write("Value of First Variable :: " + intNumOne.ToString() + "<br>");
Response.Write("Value of Second Variable :: " + intNumTwo.ToString() + "<br>");

Method 3: Without using Temp Variable and by using bitwise XOR (^ symbol in C#)

int intNumOne = 9, intNumTwo = 1;

//Swapping of numbers starts here
intNumOne ^= intNumTwo;
intNumTwo ^= intNumOne;
intNumOne ^= intNumTwo;

Response.Write("Value of First Variable :: " + intNumOne.ToString() + "<br>");
Response.Write("Value of Second Variable :: " + intNumTwo.ToString() + "<br>");

Related articles ::

1. Still Confused or if at all you are not aware of how XOR works, check out http://en.wikipedia.org/wiki/Xor_swap_algorithm to get some insight into this.

2. Temp variable usage seems to be the best method (performance wise) as per this -- http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=457179&SiteID=1

1 comment:

Joao Ferreira said...

Hi,

I've written a short note about this! You can find it in my blog. It is called Swapping the values of two variables

Cheers,
Joao