This project has been created as part of the 42 curriculum by chguerre.
push_swap is a sorting algorithm project from the 42 curriculum. The goal is to sort a stack of integers using two stacks (A and B) and a restricted set of 11 operations, producing the shortest possible sequence of moves.
The program receives a list of integers as command-line arguments and prints to stdout the operations needed to sort stack A in ascending order.
Sorting strategy:
- 1 number: nothing to do
- 2 numbers: swap if out of order
- 3 numbers: dedicated sort (at most 2 operations)
- 4+ numbers: Radix sort — each number is assigned a binary index, then sorted bit by bit using
pb(bit = 0) andra(bit = 1), restoring all elements to A after each pass
Available operations:
| Operation | Description |
|---|---|
sa |
Swap the first two elements of stack A |
sb |
Swap the first two elements of stack B |
ss |
sa and sb simultaneously |
pa |
Push the top of stack B onto stack A |
pb |
Push the top of stack A onto stack B |
ra |
Rotate stack A upward (first element goes to bottom) |
rb |
Rotate stack B upward |
rr |
ra and rb simultaneously |
rra |
Reverse rotate stack A (last element goes to top) |
rrb |
Reverse rotate stack B |
rrr |
rra and rrb simultaneously |
Performance:
| Input size | Operations | Score |
|---|---|---|
| 100 numbers | ~1300 | 2/5 |
| 500 numbers | ~7800 | 3/5 |
- GCC compiler
- GNU Make
- The
libftlibrary is included underlib/libft/
makeThis produces the push_swap executable in the project root.
make clean # remove object files
make fclean # remove object files and executable
make re # fclean + make./push_swap 5 3 1 4 2Pass integers as separate arguments or as a quoted string:
./push_swap "5 3 1 4 2"Generate a random sequence for testing:
./push_swap $(seq 1 500 | shuf | tr '\n' ' ')Using the provided checker binary:
./push_swap 5 3 1 4 2 | ./checker_linux 5 3 1 4 2Outputs OK if the sequence sorts the stack, KO otherwise.
The program prints Error to stderr and exits when given:
- Non-integer input (
"abc","12a3") - Integer overflow (outside
INT_MIN/INT_MAX) - Duplicate values
- Empty or invalid tokens
- Wikipedia — Radix sort
- Wikipedia — Sorting algorithm
- Visualgo — Sorting visualizations
- 42 Docs — push_swap subject
Claude (Anthropic) was used throughout this project as a Socratic mentor:
- Understanding concepts: binary representation, bit manipulation, radix sort theory
- Debugging: identifying pointer aliasing bugs in linked list operations, off-by-one errors in bit iteration
- Code review: Norminette compliance checks, spotting missing pointer updates in doubly linked list manipulation
- No code was generated by AI. All implementations were written by the student after guided questioning. AI was used to ask questions and validate understanding, not to produce solutions.