There is no programmer who did not come across the question:
Write a program to swap two numbers.
Swapping 2 numbers using a temporary variable is common. However, there are other ways of swapping. I am listing a few methods.
Destructuring assignment
Before swapping numbers using destructuring assignment which is introduced in ES2015, let us understand what is it.
var a, b;
[a, b] = [33, 22, 11];
console.log(a, b) // 33 22
The [a, b] = [33, 22, 11]
is the destructuring assignment that destructures array [33, 22, 11]
. The first item 33 is assigned on variable a, and the second item 22 is assigned on variable b.
Knowing this, let us now swap.
let a = 12, b = 24;
[a, b] = [b, a]; // destructuring assignment
console.log(`a = ${a}, b = ${b}`); // a = 24, b = 12
Stepwise breakdown of destructuring assignment:
- A temporary array
[b, a]
with value[24, 12]
is created. - The destructuring occurs
[a, b] = [24, 12]
, where variable a is assigned with value 24 and variable b is assigned with value 12.
Addition And Difference
This method uses simple mathematical logic to solve the problem statement.
var a = 12, b = 24;
a = a + b; // a = 36
b = a - b; // b = 36 - 24 = 12
a = a - b; // a = 36 - 12 = 24
console.log(`a = ${a}, b = ${b}`) // a = 24, b = 12
However there are limitations to this method.
- We can swap integer numbers only
- The sum of
a = a + b
in the first step should be lower thanNumber.MAX_SAFE_INTEGER
Note: You can do this swapping in one line :
num2 = num1 + ( num1 = num2 ) - num2;
I am using num1 and num2 for easy understanding
Using Multiplication And Division
The method is again a logical technique. It's nearly same as previous method but just a grade up, i.e., it uses multiplication instead of addition and division instead of subtraction.
var a = 12, b = 24;
a = a * b; // a = 288
b = a / b; // b = 288 / 24 = 12
a = a / b; // a = 288 / 12 = 24
console.log(`a = ${a}, b = ${b}`) // a = 24, b = 12
Let us discuss the limitations in this method:
- ZERO is the enemy of multiplication and division. Don't use this method if one of the number is 0. It will result in
NaN
. - Avoid
Infinity
and-Infinity
as one of the number. The answer will again result inNaN
.
Note: You can do this swapping in one line :
num2 = num1 * ( num1 = num2 ) / num2;
I am using num1 and num2 for easy understanding
Bitwise XOR operator
Let us revise the XOR operator before using this method. XOR operator returns true if 2 inputs are different. The table is shown below.
a | b | a^b |
---|---|---|
0 | 0 | 0 |
0 | 1 | 1 |
1 | 0 | 1 |
1 | 1 | 0 |
Using this logic we can swap 2 integers. The steps of swapping var a of value 5 and var b of value 9 are shown below.
- Binary equivalent of the variables a and b are: a = 5 = 0101 and b = 9 = 1001
- Store the value of
a ^ b
intoa
.
a = a ^ b
a | b | a = a ^ b |
---|---|---|
0 | 1 | 1 |
1 | 0 | 1 |
0 | 0 | 0 |
1 | 1 | 0 |
- Store the value of
a ^ b
intob
.
b = a ^ b
a | b | b = a ^ b |
---|---|---|
1 | 1 | 0 |
1 | 0 | 1 |
0 | 0 | 0 |
0 | 1 | 1 |
- Store the value of
a ^ b
intoa
.
a = a ^ b
a | b | a = a ^ b |
---|---|---|
1 | 0 | 1 |
1 | 1 | 0 |
0 | 0 | 0 |
0 | 1 | 1 |
- At this point variable a holds the value 1001 which is 9 and variable b holds the value 0101 which is 5. Hence we see the value is swapped.
var a = 12, b = 24;
a = a ^ b;
b = a ^ b;
a = a ^ b;
console.log(`a = ${a}, b = ${b}`) // a = 24, b = 12
Now let us see the limitations of this method:
- We cannot swap decimal point numbers as we just get the integer part of the number. The XOR assumes that the input is an integer and hence performs the calculations accordingly. But the floating-point number are not integers and are represented by IEEE 754 standard, which breaks the numbers in three parts: a sign bit, a group of bits representing an exponent, and another group representing a number between 1 (inclusive) and 2 (exclusive), the mantissa. Hence we get incorrect values.
- We cannot use
Infinity
and-Infinity
as they are floating point integers and face the same problem as above.
Using IIFE
An IIFE or Immediately Invoked Function Expression is a function that is executed just after the function is made. It can be used to do various jobs such as swapping 2 numbers.
var a = 12, b = 24;
a = (function (b) {
return b;
})(b, b = a)
console.log(`a = ${a}, b = ${b}`) // a = 24, b = 12
I won't prefer this method. Just included for sharing knowledge.
Using Temporary Variable
This the most common method. Here a temporary variable is used to store one of the value for swapping.
var a = 12, b = 24, temp;
temp = a; // temp = 12
a = b; // a = 24
b = a; // b = 12
console.log(`a = ${a}, b = ${b}`) // a = 24, b = 12
Conclusion
I have created a gist with the swaps which can be found here.
There are lot more methods for swapping. I have listed a few preferable choice. If you know more techniques feel free to share them in the comments.
Top comments (0)