Skip to content

Instantly share code, notes, and snippets.

@Williammer
Last active July 8, 2018 09:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Williammer/089533f835e03ea68aff to your computer and use it in GitHub Desktop.
Save Williammer/089533f835e03ea68aff to your computer and use it in GitHub Desktop.
alternative ways to swap. - several ways to swap without temp variable.
/* swap without tmp variable, merely with +/-.
Notice: this is restricted to number swap.
*/
function swap(a, b){
a = a+b;
b = a-b;
a = a-b;
}
/* math method. utilize the difference of operator priority.
Notice: this is restricted to number swap.
*/
function swap(a, b){
a= (b-a) + (b=a);
}
/* use pointer & address calc
the use of "&0x0000ffff" change the address of a to show only the higher 4 address,
since the lower 4 address is added by OS's stack/heap memory, with the basic address of 008f;
*/
if(a<b){
a=(int*)(b-a);
b=(int*)(b-(int(a)&0x0000ffff));
a=(int*)(b+(int(a)&0x0000ffff));
} else {
b=(int*)(a-b);
a=(int*)(a-(int(b)&0x0000ffff));
b=(int*)(a+(int(b)&0x0000ffff));
}
/* use ^ to swap.
Notice: this is restricted to number swap. */
function swap(a, b){
a=a^b;
b=a^b;
a=a^b;
}
/** in php we can do it in a line **/
$a=20;
$b=30;
$a ^= $b ^= $a ^= $b;
var_dump($a);
var_dump($b);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment