Skip to content
jzelada97Public

About

Sorting algorithm using two stacks with adaptive strategy selection (42 School). Implements selection sort, chunk sort, and radix sort with automatic complexity optimization.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

3 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

push_swap

Sorting algorithm project from the 42 School curriculum. The goal is to sort a list of integers using only two stacks (a and b) and a limited set of operations, generating the shortest possible instruction sequence.

The program implements four sorting strategies of different complexity and automatically selects the most appropriate one based on the input's degree of disorder.


Compilation

make          # compiles push_swap
make bonus    # compiles checker
make clean    # removes .o files
make fclean   # removes .o files and binaries
make re       # full recompile

Usage

./push_swap [--simple | --medium | --complex | --adaptive] [--bench] <integers>
Flag Description
--simple Forces the O(n²) algorithm
--medium Forces the O(n√n) algorithm
--complex Forces the O(n log n) algorithm
--adaptive Automatic selection based on disorder index (default)
--bench Displays performance metrics on stderr after sorting

Checker (bonus)

The checker program verifies that the operations generated by push_swap correctly sort the stack:

ARG="4 67 3 87 23"
./push_swap $ARG | ./checker $ARG
# OK
  • Prints OK if the stack is sorted and b is empty
  • Prints KO if not sorted
  • Prints Error on stderr for invalid arguments or unknown instructions

Examples

# Basic sorting
./push_swap 5 3 1 4 2

# String input (quoted)
./push_swap "5 3 1 4 2"

# Force simple strategy and count operations
./push_swap --simple 5 4 3 2 1 | wc -l

# Verify with checker
ARG="4 67 3 87 23"
./push_swap --complex $ARG | ./checker $ARG

# Benchmark mode
./push_swap --bench 5 3 1 4 2 2>/dev/null

# Test with 500 random numbers
shuf -i 0-9999 -n 500 > args.txt
./push_swap $(cat args.txt) | wc -l

Error Handling

The program prints Error on stderr and exits for:

  • Non-integer arguments
  • Arguments exceeding int range
  • Duplicate values
  • Invalid flags
  • More than one strategy flag at a time

Available Operations

Operation Description
sa Swap the first two elements of a
sb Swap the first two elements of b
ss sa + sb simultaneously
pa Push top of b to top of a
pb Push top of a to top of b
ra Rotate a upward (first becomes last)
rb Rotate b upward
rr ra + rb simultaneously
rra Reverse rotate a (last becomes first)
rrb Reverse rotate b
rrr rra + rrb simultaneously

Algorithms

1. Simple — O(n²)

Strategy: Selection sort adapted for two stacks.

Each iteration finds the minimum in stack a, rotates it to the top (using ra or rra depending on shortest path), and pushes it to b. Once all elements are in b, they are pushed back to a. For sizes <= 5, optimized special cases are used (sort_two, sort_three, sort_five).


2. Medium — O(n√n)

Strategy: Chunk sort.

The value range is divided into √n uniform blocks (chunks) scaled by a 1.4 factor. Each pass pushes elements belonging to the current chunk to b, minimizing rotations. Once all chunks are in b, a is reconstructed by extracting maximums with pa.


3. Complex — O(n log n)

Strategy: Radix sort LSD (Least Significant Digit) with index representation.

Values are normalized to indices 0..n-1 for binary processing. For each bit (LSB to MSB), elements are distributed between a and b based on the bit value, then regrouped. Number of passes is log₂(n).


4. Adaptive — automatic selection

Strategy: Combines the three algorithms above based on a disorder index computed before any operations.

The disorder index measures the fraction of pairs (i, j) with i < j where a[i] > a[j]:

disorder = number of inversions / total possible pairs × 100
Disorder Range Algorithm Complexity
< 20% Simple (nearly sorted) O(n²)
20% - 50% Chunk sort O(n√n)
>= 50% Radix sort LSD O(n log n)

Benchmark Mode (--bench)

When --bench is enabled, the program prints to stderr:

[bench] disorder: 73.45%
[bench] strategy: complex (O(n*log(n)))
[bench] total ops: 4821
[bench] sa: 0  sb: 12  ss: 0
[bench] pa: 500  pb: 500
[bench] ra: 1203  rb: 892  rr: 0
[bench] rra: 714  rrb: 1000  rrr: 0

Performance

Input Minimum Good Excellent
100 numbers < 2000 ops < 1500 ops < 700 ops
500 numbers < 12000 ops < 8000 ops < 5500 ops
Strategy Complexity 100 elements 500 elements
simple O(n²) ~1477 ops Not recommended
medium O(n√n) ~561 ops ~5000 ops
complex O(n log n) ~1084 ops ~6784 ops
adaptive Variable Depends on disorder Depends on disorder

Project Structure

push_swap/
├── Makefile
├── includes/
│   ├── push_swap.h
│   ├── stack.h
│   ├── operations.h
│   ├── algorithms.h
│   └── bench.h
├── srcs/
│   ├── main/
│   │   ├── main.c
│   │   ├── main_utils.c
│   │   ├── checker_bonus.c
│   │   └── checker_utils_bonus.c
│   ├── parsing/
│   │   ├── parsing.c
│   │   └── parsing_utils.c
│   ├── operations/
│   │   ├── operations_swap.c
│   │   ├── operations_push.c
│   │   ├── operations_rotate.c
│   │   └── operations_reverse_rotate.c
│   ├── algorithms/
│   │   ├── algorithm_utils.c
│   │   ├── algorithm_position.c
│   │   ├── sort_simple.c
│   │   ├── sort_medium.c
│   │   ├── sort_complex.c
│   │   └── sort_adaptive.c
│   └── utils/
│       ├── stack/
│       ├── disorder/
│       └── bench/
└── libft/

Built With

  • Language: C (C99)
  • Build: Make
  • Standard: 42 Norm compliant
  • Platform: Linux / macOS

Context

Developed as part of the 42 Madrid curriculum. The project focuses on algorithmic complexity, stack-based data structures, and optimization under strict constraints.

About

Sorting algorithm using two stacks with adaptive strategy selection (42 School). Implements selection sort, chunk sort, and radix sort with automatic complexity optimization.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages