Push_swap is a 42 School project that challenges students to create an efficient sorting algorithm using two stacks and a limited set of operations. The goal is to sort a given list of integers using the fewest possible moves.
The program takes a list of integers as input and uses two stacks, A and B, to sort them. The available operations are:
sa
: Swap the first two elements of stack Asb
: Swap the first two elements of stack Bss
: Performsa
andsb
simultaneouslypa
: Push the top element from stack B to stack Apb
: Push the top element from stack A to stack Bra
: Rotate stack A (move the top element to the bottom)rb
: Rotate stack Brr
: Performra
andrb
simultaneouslyrra
: Reverse rotate stack A (move the bottom element to the top)rrb
: Reverse rotate stack Brrr
: Performrra
andrrb
simultaneously
The program outputs the list of operations needed to sort the input.
- Clone the repository:
git clone https://github.com/yourusername/Push_swap-42.git
- Navigate to the project directory:
cd Push_swap-42
- Compile the project:
make
Run the program with a list of integers as arguments:
./push_swap 4 67 3 87 23
For checker (if implemented):
ARG="4 67 3 87 23"; ./push_swap $ARG | ./checker $ARG
This implementation uses a combination of algorithms depending on the input size:
- For 2 numbers: Simple swap if needed
- For 3 numbers: Hardcoded optimal solution
- For 4-5 numbers: Insertion sort
- For larger sets: Radix sort
The core sorting logic can be found in the following files:
startLine: 15
endLine: 29
startLine: 31
endLine: 73
To better understand how the algorithm works, you can use the Push_swap Visualizer. Here's a snapshot of the visualization:
This image demonstrates the state of both stacks at different stages of the sorting process.
Special thanks to @o-reo for their excellent Push_swap Visualizer, which greatly helped in understanding and optimizing the algorithm.
Feel free to contribute, report issues, or suggest improvements!