DEV Community

Discussion on: How can you swap two variables without using a third?

Collapse
 
sadarshannaiynar profile image
Adarsh
if (x == y) return;
x = x ^ y
y = x ^ y
x = x ^ y

Bitwise operators for the win.

Collapse
 
theoutlander profile image
Nick Karnik

The swap with bitwise operators will be the fastest at the hardware level. :)

Collapse
 
sadarshannaiynar profile image
Adarsh

Yes. Whenever you can achieve something using bitwise operations I always prefer that.

Collapse
 
almostconverge profile image
Peter Ellis

Rather disappointingly, in most modern hardware it's the one with the temp variable that is fastest.

Thread Thread
 
theoutlander profile image
Nick Karnik

Depending on the architecture and compiler, they end up using three registers to do a swap under the hood I think.

Thread Thread
 
almostconverge profile image
Peter Ellis

Yes, but the idea is that you do this in assembly. It was a common trick because it saved a register and (at worst) it ran in the same number of cycles.

Collapse
 
codemouse92 profile image
Jason C. McDonald • Edited

When I started going through the comments, I was actually thinking "what about bitwise xor?" And sure enough, here it is. ^,^

Collapse
 
ptdecker profile image
P. Todd Decker

JavaScript, by nature, stores all numbers as double-precision IEEE 754 floating point numbers. The 52 bits of the fractional portion is used to store integers. This results in 'maximum safe integer' of 2^53 - 1. Further complicating things is that JavaScript's bitwise operators only deal with the lowest 32 bits of JavaScript's 54-bit integers. So the bitwise approach will not work on big integers in JavaScript.

Collapse
 
d4vecarter profile image
Dave Carter™

I guess BigInt new primitive proposal will do the trick :)

Collapse
 
nestedsoftware profile image
Nested Software • Edited

This is a rather beautiful "bit" of problem solving :)

It will work for both integers and floating points, positive and negative, and there is no issue with overflow. If someone can figure this out on their own, I think that's quite impressive. Most of us just know it from having seen it before though.

Collapse
 
theoutlander profile image
Nick Karnik

That's true. My initial solution to it was using addition/subtraction and once I got the concept of diffs, I was able to deduce a solution using bit manipulation.