Fatih Çil

Self-Taught Developer

Software Engineer

Programmer

Game Developer

Fatih Çil

Self-Taught Developer

Software Engineer

Programmer

Game Developer

Blog Post

Push_swap: Sorting With Only Two Stacks

May 10, 2022 École 42

Hi! Push_swap looks innocent: sort a list of integers. The catch — your only tools are two stacks (A and B) and a tiny instruction set (sa, pb, ra, rrr…), and your grade depends on how few operations you use.

From bubble sort to chunks

My first naive attempt produced tens of thousands of moves. The project is really an algorithms playground: you analyse the cost of each operation, normalize the input to ranks, and then design a strategy. I ended up with a chunk-based approach — splitting the values into ranges, pushing them to stack B in groups, then pulling them back in order while rotating whichever direction is cheaper.

Why it matters

It was the first time I measured my code instead of just running it: counting operations, profiling worst cases against the grading thresholds (700 ops for 100 numbers, 5500 for 500), and iterating on the algorithm rather than the implementation. That habit — benchmark first, optimize second — stayed with me all the way into game development, where frame budgets replace operation counts.

The code lives in my 42Cursus repository.

42 push_swap badge

Related Posts