Skip to content

ikrishagarwal/silly-swap

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

5 Commits
 
 
 
 
 
 
 
 

Repository files navigation

Swapping variables?

wakatime (doesn't include thinking hours)

This repository walks though on my implementation of swapping two variables without using a temporary variable or arithmetic operations or XOR.

Algorithm

  1. Initialize two variables, a and b, with the values to be swapped.
  2. Shift a to the left by the number of bits in b.
  3. Perform a bitwise OR between a and b, storing the result in b.
  4. Perform a bitwise AND between b and a sequence of 1s matching the number of bits in b, storing the result in a.
  5. Shift b to the right by the number of bits in b.
  6. Done!

Visual Representation of the algorithm

Code

Look at main.c

Complexity

  • Time complexity: O(1)
  • Space complexity: O(1)

Limitations

This code doesn't work for negative numbers as of now.

No limitations! Apart from the standard space issue same as with arithmetic operations.

Author

About

Swap two variables without a third variables or any arithmetic or XOR function.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages