Williammer
5/9/2014 - 9:09 AM

alternative ways to swap. - several ways to swap without temp variable.

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);