Insight

Wednesday, September 12, 2012

Swap 2 variables without using a temp variable

Swap two variable contents without using a temp variable

Standard approach:
 a=a+b,
 b=a-b,
 a=a-b


XOR algorithm bitwise operators:
 a=a^b,
 b=a^b,
a=a^b.

How does XOR works ?
true - true = false
true- false = true
false- false = false
false-true = true

Wiki for XOR swap algorithm:
http://en.wikipedia.org/wiki/XOR_swap_algorithm
Posted by Geek at 8:02 PM
Email ThisBlogThis!Share to XShare to FacebookShare to Pinterest

No comments:

Post a Comment

Newer Post Older Post Home
Subscribe to: Post Comments (Atom)

Blog Archive

  • ►  2014 (4)
    • ►  January (4)
  • ►  2013 (9)
    • ►  December (7)
    • ►  November (1)
    • ►  January (1)
  • ▼  2012 (26)
    • ►  November (3)
    • ▼  September (22)
      • Eclipse IAdaptable pattern – Show Properties for I...
      • Chain of Responsibility Design pattern
      • Adapter Design Pattern
      • Comparable and Comparator in Java
      • Reference Objects and Garbage Collection
      • Database ACID Properties
      • Thread concepts
      • How run a JAR file
      • Swap 2 variables without using a temp variable
      • Big O Notation - Illustration
      • Basics of Big O Notation
      • Principles of Designing
      • Java Links
      • Classical operations on Set
      • Thread Puzzle
      • Avoiding dead locks
      • Java Puzzle
      • Singleton Design Pattern
      • Producer Consumer Problem
      • Thread Local Example
      • Reverse of single linked list
      • Dead lock using threads
    • ►  August (1)
Ethereal theme. Powered by Blogger.