Push Swap
An algorithmic project to sort data on a stack with a limited set of instructions, optimized for the lowest number of operations.
2021-09-01
algorithmsOpen GitHub

Push Swap
Given a list of integers on stack A, output the shortest sequence of operations to sort them using only two stacks and a fixed instruction set. No comparison sorts, no built-ins. The fewer operations, the better.
The instruction set
| Instruction | What it does |
|---|---|
| sa / sb / ss | Swap top two elements of A / B / both |
| pa / pb | Push top of B to A / top of A to B |
| ra / rb / rr | Rotate A up / B up / both |
| rra / rrb / rrr | Reverse rotate A / B / both |
The algorithm
- Normalize the integers to their rank (0 to N-1), which removes value gaps and simplifies comparisons
- Small inputs (2-3 elements) use hardcoded optimal sequences
- Larger inputs push elements to stack B in ranked chunks, then pull them back to A using cost-optimized rotations
The cost model looks at how many moves each element needs to reach its correct position in both stacks at once, and always picks the cheapest next move.
Performance
| Input size | Max operations |
|---|---|
| 3 numbers | 3 |
| 5 numbers | 12 |
| 100 numbers | 700 |
| 500 numbers | 5500 |
Running it
./push_swap 4 67 3 87 23
# verify correctness
./push_swap 4 67 3 87 23 | ./checker 4 67 3 87 23
# OK
# count operations
./push_swap 4 67 3 87 23 | wc -lmake # builds push_swap
make bonus # builds the checkerSCREENSHOTS // 01 FRAMES

01 / 01