Sort Three Numbers Without Conditionals
Updated: Oct 12, 2025
Sort 3 Integers without using if condition (use only Max())
Problem
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).
Examples
Example 1
Input:
a = 4, b = 1, c = 9
Output:
[1, 4, 9]
Explanation:
Using only `max()` and arithmetic we compute min, mid and max.
Example 2
Input:
a = 5, b = 5, c = 2
Output:
[2, 5, 5]
Explanation:
Duplicates are handled naturally by the formulas.
Solution
Method 1 - Use Max() and arithmetic
Intuition
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.
Approach
- Compute
max = max(a, max(b, c)). - Compute
min = -max(-a, -b, -c). - Compute
mid = a + b + c - max - min. - Return
[min, mid, max].
Code
C++
#include <algorithm>
#include <array>
using namespace std;
class Solution {
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};
}
};
Go
package main
func sort3(a, b, c int) [3]int {
mx := max(a, max(b, c))
mn := -max(-a, max(-b, -c))
mid := a + b + c - mx - mn
return [3]int{mn, mid, mx}
}
func max(x, y int) int { if x > y { return x }; return y }
Java
import java.util.Arrays;
class Solution {
public int[] 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;
return new int[]{mn, mid, mx};
}
}
Kotlin
class Solution {
fun sort3(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)
}
}
Python
from typing import List
class Solution:
def sort3(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]
Rust
pub struct Solution;
impl Solution {
pub fn sort3(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]
}
}
Typescript
export class Solution {
sort3(a: number, b: number, c: number): number[] {
const mx = Math.max(a, Math.max(b, c));
const mn = -Math.max(-a, Math.max(-b, -c));
const mid = a + b + c - mx - mn;
return [mn, mid, mx];
}
}
Complexity
- ⏰ Time complexity:
O(1)– A constant number of arithmetic andmax()operations. - 🧺 Space complexity:
O(1)– Only a few local variables are used.