Home > Programming > How to swap 2 variables without temp variable

How to swap 2 variables without temp variable

October 23rd, 2007 admin Leave a comment Go to comments

Swapping 2 variables requires a third temp variable, this is how it is implemented with 3 variables (I have implemented this in PHP, the same logic can be used in any language):

<?php

$a = 5;
$b = 7;
$temp = $a;
$a = $b;
$b = $temp;

echo “$a : $b”;

?>




This is how we would do this using only 2 variables

<?php

$a = 5;
$b = 7;
$a = $a + $b; // $a becomes 12
$b = $a – $b; // $a becomes 5
$a = $a – $b; // $a becomes 7

echo “$a : $b”;

?>

Categories: Programming Tags:

Warning: session_start(): Cannot send session cookie - headers already sent by (output started at /home/sunilb/www.sunilb.com/wp-content/plugins/all-in-one-seo-pack/aioseop.class.php:245) in /home/sunilb/www.sunilb.com/wp-content/plugins/mycaptcha/MyCaptcha.php on line 41

Warning: session_start(): Cannot send session cache limiter - headers already sent (output started at /home/sunilb/www.sunilb.com/wp-content/plugins/all-in-one-seo-pack/aioseop.class.php:245) in /home/sunilb/www.sunilb.com/wp-content/plugins/mycaptcha/MyCaptcha.php on line 41
  1. P.Kumaran
    November 1st, 2007 at 15:18 | #1

    How to swap 2 variables without temp variable

    for eg:-

  2. November 16th, 2007 at 23:39 | #2

    Only problem is that it only works with numbers and not strings, arrays, or other variables types. The only way you can swap those efficiently is with the third variable.

  3. Stephan
    November 17th, 2007 at 18:33 | #3

    nice!

  4. November 21st, 2007 at 14:32 | #4

    Nice post, I like how you describe the solution in simple arithmetic terms; most textbooks use the bit-mask syntax, which I find less intuitive.

    Of course, one could also say that this approach of swapping 2 integer variables without a third temporary variable is in fact using a third temporary variable composed of the unused higher-order bits of the 2 input variables. If the 2 variables used enough of the bits of their data-type, this swap would not work correctly. Exactly how big the values can get and still be accurately swapped this way I leave as an exercise for the reader. ;-)

  5. vidhya
    April 17th, 2008 at 18:13 | #5

    It is very useful to all those programmers to improve logical thinking like this.

  1. No trackbacks yet.
Enter this code to leave comment (Sorry, but bots get me crazy :) )