Given three integers a, b, and c, sort them in non-decreasing order without using any if/conditional branching. The allowed primitive is the max() function (and arithmetic).
We can compute the maximum with max(a, max(b, c)). The minimum can be computed by negating all values and taking a max: min = -max(-a, -b, -c). The middle value follows from mid = a + b + c - max - min.
#include<algorithm>#include<array>usingnamespace std;
classSolution {
public: array<int, 3> sort3(int a, int b, int c) {
int mx = max(a, max(b, c));
int mn =-max(-a, max(-b, -c));
int mid = a + b + c - mx - mn;
return {mn, mid, mx};
}
};
import java.util.Arrays;
classSolution {
publicint[]sort3(int a, int b, int c) {
int mx = Math.max(a, Math.max(b, c));
int mn =-Math.max(-a, Math.max(-b, -c));
int mid = a + b + c - mx - mn;
returnnewint[]{mn, mid, mx};
}
}
1
2
3
4
5
6
7
8
classSolution {
funsort3(a: Int, b: Int, c: Int): IntArray {
val mx = maxOf(a, maxOf(b, c))
val mn = -maxOf(-a, maxOf(-b, -c))
val mid = a + b + c - mx - mn
return intArrayOf(mn, mid, mx)
}
}
1
2
3
4
5
6
7
8
from typing import List
classSolution:
defsort3(self, a: int, b: int, c: int) -> List[int]:
mx = max(a, max(b, c))
mn =-max(-a, max(-b, -c))
mid = a + b + c - mx - mn
return [mn, mid, mx]
1
2
3
4
5
6
7
8
9
pubstructSolution;
impl Solution {
pubfnsort3(a: i32, b: i32, c: i32) -> [i32; 3] {
let mx = std::cmp::max(a, std::cmp::max(b, c));
let mn =-std::cmp::max(-a, std::cmp::max(-b, -c));
let mid = a + b + c - mx - mn;
[mn, mid, mx]
}
}