Push_swap is a challenging algorithmic project from the 42 School curriculum that tests students' ability to implement efficient sorting algorithms. The task involves sorting a stack of integers using two stacks (A and B) with a limited set of operations, while minimizing the number of moves.
Our sorting strategy combines elegant solutions for small datasets with a powerful chunk-based approach for larger sets. Here's how it works:
- 2 elements:
sa
when needed - 3 elements: Optimized three-number sorting patterns
- 4 elements: Strategic pushing and rotation sequence
- 5 elements: Specialized five-number sorting algorithm
The algorithm operates in two main phases:
The algorithm implements a dynamic chunking strategy:
-
Window Calculation 📏
- Dynamic window size:
max = 0.05 * stack_size + 10
- Window continuously slides up as elements are pushed
- Minimum threshold tracks the lower bound of current chunk
- Dynamic window size:
-
Element Distribution ⚡
// For each element in stack A: if (element_index >= min && element_index <= max) push to B // pb else if (element_index < min) push to B and rotate B // pb, rb else rotate A // ra
-
Optimization Features ⚙️
- Elements below minimum are pushed and rotated for better positioning
- Window size adapts to total stack size for optimal performance
- Smart rotation direction selection
The algorithm rebuilds the sorted stack through:
-
Maximum Element Location 🎯
- Efficiently finds the position of the maximum index in Stack B
- Calculates optimal rotation direction
-
Efficient Movement ⚡
while (elements in stack B) if (top_element is current_max) push to A // pa else if (max_position < size/2) rotate B up // rb else rotate B down // rrb
-
Position Optimization 🔄
- Chooses rotation direction based on element position
- Minimizes operations through path optimization
- Time Complexity: O(n log n) average case
- Space Complexity: O(n) using two stacks
- Operation Counts 📊:
- 100 numbers: < 700 operations
- 500 numbers: < 5500 operations
sa
: Swap first two elements of stack Asb
: Swap first two elements of stack Bss
: sa and sb simultaneouslypa
: Push top element from stack B to stack Apb
: Push top element from stack A to stack Bra
: Rotate stack A uprb
: Rotate stack B uprr
: ra and rb simultaneouslyrra
: Rotate stack A downrrb
: Rotate stack B downrrr
: rra and rrb simultaneously
# Compilation
make
# Basic usage
./push_swap 4 67 3 87 23
# With checker (bonus)
ARG="4 67 3 87 23"; ./push_swap $ARG | ./checker $ARG
The checker program is a crucial tool for validating the sorting operations of push_swap. Here's how it works:
-
Input Processing
- Reads the initial stack configuration
- Accepts push_swap operations via standard input
- Validates operation format and sequence
-
Operation Execution
- Performs each operation on its own copy of the stacks
- Maintains operation integrity and stack consistency
- Tracks stack state after each operation
-
Result Validation ✅
- Verifies final stack order
- Checks if Stack B is empty
- Returns appropriate status:
OK
: Stack is perfectly sortedKO
: Stack is not sorted or Stack B not emptyError
: Invalid operations detected
# Basic checker usage
./checker 3 2 1
sa
rra
pb
pa
OK
# Pipe with push_swap
./push_swap 3 2 1 | ./checker 3 2 1
# Multiple number testing
ARG=$(shuf -i 1-100 -n 50 | tr "\n" " "); ./push_swap $ARG | ./checker $ARG
Robust error checking for:
- Non-integer inputs ❌
- Duplicate numbers 🔄
- Integer overflow/underflow 📊
- Empty input 💨
- Invalid argument formats 🚫
- Comprehensive test suite included
- Edge case handling
- Performance benchmarking tools
- Memory leak checking
- C compiler (gcc/clang)
- Make
- Standard C library
This project is distributed under the MIT license. See LICENSE
file for more information.
📚 Part of the 42 School Curriculum
Made with ❤️ and lots of ☕