Live data from Hacker News

Swapping two Numbers without Temporary Variables

garrit.xyz

1–10 of 93 posts

Re: Swapping two Numbers without Temporary Variables

#4

This is a variation on xor-swap, but one that suffers from over(/under)flow https://en.wikipedia.org/wiki/XOR_swap_algorithm#Variations

The classic use of XOR-swap was to traverse a tree without needing a stack. As you traverse the tree, the forward links are swapped with backward links, so you can find your way back. Used in the mark phase of some early garbage collectors.

Re: Swapping two Numbers without Temporary Variables

#8
post #6
post #5

Or, in Python a, b = b, a Or Rust: (a, b) = (b, a);

These aren't algorithms. The language is still doing something under the hood to do the swap.

Was that the problem statement? Come up with an algorithm to swap two numbers?

Re: Swapping two Numbers without Temporary Variables

#9
post #4

This is a variation on xor-swap, but one that suffers from over(/under)flow https://en.wikipedia.org/wiki/XOR_swap_algorithm#Variations

The classic use of XOR-swap was to traverse a tree without needing a stack. As you traverse the tree, the forward links are swapped with backward links, so you can find your way back. Used in the mark phase of some early garbage collectors.

can you explain this please (your comments are lovely btw)

Re: Swapping two Numbers without Temporary Variables

#10
post #4

This is a variation on xor-swap, but one that suffers from over(/under)flow https://en.wikipedia.org/wiki/XOR_swap_algorithm#Variations

The classic use of XOR-swap was to traverse a tree without needing a stack. As you traverse the tree, the forward links are swapped with backward links, so you can find your way back. Used in the mark phase of some early garbage collectors.

That's pointer reversing but as I've seen it, it usually doesn't involve xor swap. It is still used in some gc's.
Post reply on HN