forked from rampatra/Algorithms-and-Data-Structures-in-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMaxWithoutBranching.java
46 lines (40 loc) · 1.7 KB
/
MaxWithoutBranching.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package com.rampatra.bits;
/**
* Created by IntelliJ IDEA.
*
* @author rampatra
* @since 6/8/15
* @time: 5:41 PM
* @link: http://graphics.stanford.edu/~seander/bithacks.html#IntegerMinOrMax
*/
public class MaxWithoutBranching {
public static int getMinWithoutBranching(int a, int b) {
return b ^ ((a ^ b) & -((a < b) ? 1 : 0));
}
public static int getMaxWithoutBranching(int a, int b) {
return a ^ ((a ^ b) & -((a < b) ? 1 : 0));
}
public static void main(String[] args) {
System.out.println(getMinWithoutBranching(5, 6));
System.out.println(getMinWithoutBranching(-5, -6));
System.out.println(getMinWithoutBranching(-5, 6));
System.out.println(getMinWithoutBranching(5, -6));
System.out.println(getMinWithoutBranching(0, 0));
System.out.println(getMaxWithoutBranching(5, 6));
System.out.println(getMaxWithoutBranching(-5, -6));
System.out.println(getMaxWithoutBranching(-5, 6));
System.out.println(getMaxWithoutBranching(5, -6));
System.out.println(getMaxWithoutBranching(0, 0));
}
}
/**
* EXPLANATION:
* On some rare machines where branching is very expensive and no condition move
* instructions exist, the above expression might be faster than the obvious
* approach, r = (x < y) ? x : y, even though it involves two more instructions.
* (Typically, the obvious approach is best, though.) It works because if x < y,
* then -(x < y) will be all ones, so r = y ^ (x ^ y) & ~0 = y ^ x ^ y = x.
* Otherwise, if x >= y, then -(x < y) will be all zeros, so r = y ^ ((x ^ y) & 0) = y.
* On some machines, evaluating (x < y) as 0 or 1 requires a branch instruction,
* so there may be no advantage.
*/