Sort 3 numbers without comparison operators.

Had this problem for an interview. The goal is to sort an array of 3 integers, without any comparison operators. This includes ==, <=, >=, etc, if else statements (they implicitly use comparison operators), and built-in functions that use comparison operators, such as min() and max(). Bit operators do not count as comparison operators (since they avoid branching, which is one of the premise for this problem).

Example:

Input = [1, 3, 2]
Output = [1, 2, 3]

Input = [-2147483646, 2147483647, 0]
Output = [-2147483646, 0, 2147483647]

To be clear, all comparison operators cannot appear anywhere in the code.

Edit:
I guess I wasn't too clear about the premise, but the goal of the interviewer is to get me to write a "branchless" solution. By branchless I mean the code I write will not cause branching in CPU. This means no if else, no loops, no comparisons.

I'll post my solution later (interviewer was happy with my solution, but didn't have much time to discuss it because out of time). Hopefully someone comes up with a better solution, I thought this problem was very interesting.

Comments (6)