temp = x;
x = y;
y = temp;
Tom showed me a different way. A tricky way. A way that only really works with integer values.
y = y ^ x;
x = y ^ x;
y = y ^ x;
The caret ( ^ ) is the symbol for an Exclusive Or for those of you not current in C#.
It’s Truth table looks something like the image on the right. Of course when Tom showed me this I had to try it out. I used the values X = 10 and Y = 3. In Binary the results looked something like this:
Naturally I had to write a program to double check my math.
This is all fun and interesting in a geeky sort of way. But is it a good idea? No so much. For one thing it is tricky, unusual and can easily confuse people. For another there is no speed gain. In fact the XOR operation is actually slower than the copy to another location operation. Not by a lot. They can both be register operations which are the fastest sort of CPU operations. But without a good performance gain there is no real reason to use the XOR method (even if it being confusing were not enough reason) over the swap operation. Lastly the fact that this is not as general purpose as the swap method is the nail in the coffin as far as I’m concerned.
But it sure is cool. In a geeky sort of way.
Ah but you need 3 registers for the swap method and 2 for the other. In days gone by when processors had less registers this was possibly a deciding factor.
ReplyDeletehttp://en.wikipedia.org/wiki/XOR_swap_algorithm#Reasons_for_use_in_practice
These days though... not important and just an annoying interview question
I thought about the three registers issue when I was doing this. There was a time when that was a lot more important than it was today. A lot depends on the specific hardware, microcoding and a lot of other things that are more hardware dependent than software. One could imagine a design that made swapping faster but I don't imagine anyone optimizing for that these days.
ReplyDelete