push_swap
42 · Rank 2
Mission Briefing
Sorts a stack of integers using two stacks and eleven allowed moves, in as few moves as possible. My solution uses a cost-based greedy algorithm that scores every possible move before making one.
Skills shown
- Algorithm design
- Complexity analysis
- Linked lists in C
Built with
- C
- Makefile
Loading…
This is my original push_swap C code, compiled to WebAssembly. Every move you make runs my C functions.
How it works
Only two stacks (a and b) and moves like sa, pb, ra and rrr are allowed. Two numbers need at most one sa, and three numbers use a hard-coded sort_three. Larger inputs push everything except three numbers onto b, then bring them back one at a time.
For each node in b, the program finds its target in a (the smallest number bigger than it), then adds up how many rotations both stacks need to line up. The cheapest node wins, and when its moves are executed, rotations that go the same way on both stacks are merged into rr or rrr:
In outline (simplified from the real loop):
calculate_costs rotations needed for every node in b
find_best_move pick the cheapest node overall
do_rotations line both stacks up, sharing rr / rrr where possible
pa push it back onto a
A final rotate_to_min puts the smallest number on top.
What I learned
Measuring before optimising. Counting moves on random inputs of 100 and 500 numbers showed where the greedy choice paid off and where it didn’t.