Skip to content

Commit 3f72398

Browse files
authored
Merge pull request thuva4#356 from AtoMc/master
Add Xor swap for Java
2 parents 27bdd3a + 7dfb28b commit 3f72398

File tree

2 files changed

+29
-1
lines changed

2 files changed

+29
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,7 @@ TernarySearch | :+1: |:+1: | | :+1: | :+1: | | | |
6161
Topological Sort | | | | | :+1: | | | |
6262
Segmented Sieve |:+1:| :+1: | | | :+1: | | | |
6363
Union Find |:+1:|:+1:| | | | | | |
64+
Xor swap |:+1:| | | | | | | |
6465

6566

6667
### List of Algorithms :
@@ -769,7 +770,7 @@ Union Find |:+1:|:+1:| | | | | | |
769770

770771
* Xiaolin Wu's line algorithm : algorithm for line antialiasing.
771772

772-
* Xor swap algorithm : swaps the values of two variables without using a buffer
773+
* [Xor swap algorithm](XorSwap) : swaps the values of two variables without using a buffer
773774

774775
* Yamartino method : calculate an approximation to the standard deviation σθ of wind direction θ during a single pass through the incoming data
775776

XorSwap/Java/XorSwap.java

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
/**
2+
* XOR swap is an algorithm that uses the XOR bitwise operation to swap
3+
* values of distinct variables without using a temporary variable.
4+
*
5+
* @author Atom
6+
* @see <a href="https://en.wikipedia.org/wiki/XOR_swap_algorithm">XOR swap</a>
7+
*/
8+
public class XorSwap {
9+
10+
public static void main(String[] args) {
11+
for (int i = -1, j = 3; i <= 3; i++, j--) {
12+
int x = i;
13+
int y = j;
14+
System.out.print("x = " + x + ", y = " + y);
15+
16+
// Xor swap. Swap values without using a temporary variable
17+
if (x != y) {
18+
x ^= y;
19+
y ^= x;
20+
x ^= y;
21+
}
22+
23+
System.out.println(", swap(x, y) -> x = " + x + ", y = " + y);
24+
}
25+
}
26+
27+
}

0 commit comments

Comments
 (0)