How can you sort numbers in a Rec Room circuit?

I would like to sort a total of 4 numbers in a Rec Room circuit. Ideally, I'd like to do it in a single tick, but a multi-tick solution might be workable.

The inputs would be 4 separate pins and the outputs would be 4 pins as well. When the sort is complete, the output pins should contain all of the numbers on the input pins but sorted numerically.


For small values of n, where n is the number of elements you want to sort, you should probably use a Sorting Network. Visualization from Wikipedia for the optimal sorting network for n=4:

Sorting Network

Here is an implementation of it. I also published an invention "Sorting Networks" with optimal size sorting networks for n=[2,7].

Sorting Network


Sorting numbers in Rec Room becomes very expensive very quickly. However, for a small number of N inputs, it can be very possible.

The solution I've arrived at may not be the best solution, but it is a solution that can be easily expanded to support larger N (albeit at a cost). The solution for N=2 is pretty straightforward:

N=2 Sort

This circuit sorts the values from the Red and Green pin of the variable chip and outputs them on the two plus chips at the right in increasing order from top to bottom. You might notice that this performs what is known as a "Swap" in an array, and we can use this operation to sort a larger N of inputs by modeling if after Bubble Sort.

Bubble Sort requires N(N-1)/2 swaps to completely sort an array of N numbers, therefore, for an array of N=3, we should be able to sort it with 3 copies of the circuit above. The resulting circuit looks as follows- I've highlighted the 3 swap circuits in red squares.

N=3 Sort

The solution for N=4 can follow the same logic as the solution for N=3, but with 6 comparisons instead of just 3. Add another column of 3 swap circuits to the left of the column of 2 swap circuits and connect them appropriately.

Of course, you can keep going for larger N; N=5 would take 10 swaps which with 5 chips per swap, would require 50 chips.

You can view and play with the circuits outlined in this post here.