Skip to main content

Welcome to Push Swap

Push Swap is a highly optimized sorting algorithm that solves the stack sorting problem with minimal operations. Built as a 42 School project, it implements the Turkish algorithm to achieve optimal performance across stacks of any size.

Quick Start

Get up and running with Push Swap in minutes

Algorithm Overview

Learn how the Turkish algorithm works

Operations Reference

Explore all available stack operations

Build from Source

Compile and test Push Swap locally

Key Features

Turkish Algorithm

Implements the advanced Turkish algorithm for optimal sorting efficiency

Cost Analysis

Analyzes and minimizes the number of operations needed

Median Optimization

Uses median-based strategies to reduce rotation costs

Target Identification

Smart target node selection for efficient moves

Any Stack Size

Handles 2, 3, or thousands of elements efficiently

Error Handling

Validates input and handles edge cases gracefully

How It Works

Push Swap uses two stacks (A and B) and a limited set of operations to sort integers in ascending order. The algorithm:
  1. Analyzes the input - Validates integers and detects if already sorted
  2. Applies specialized sorting - Uses optimized algorithms for small stacks (2-3 elements)
  3. Executes Turkish algorithm - For larger stacks, employs cost analysis and target selection
  4. Minimizes operations - Chooses the cheapest moves to achieve sorted order
The Turkish algorithm is particularly efficient for sorting operations, often requiring fewer moves than traditional sorting approaches.

Available Operations

Push Swap supports 11 stack manipulation operations:

Swap Operations

sa, sb, ss - Swap top two elements

Push Operations

pa, pb - Move elements between stacks

Rotate Operations

ra, rb, rr - Shift elements upward

Reverse Rotate

rra, rrb, rrr - Shift elements downward

Get Started

1

Installation

Clone the repository and compile the program
git clone https://github.com/ibon-ira/Push_swap-42-turk-algorithm-.git
cd Push_swap-42-turk-algorithm-
make
2

Run Push Swap

Execute with a list of integers to sort
./push_swap 3 2 5 1 4
3

View Operations

The program outputs the sequence of operations needed to sort the stack

Learn More

Turkish Algorithm Deep Dive

Understand the algorithm’s cost analysis and optimization strategies

Implementation Details

Explore the data structures and core implementation

Usage Examples

See real-world examples and test cases

Contributing

Learn how to contribute to the project

Build docs developers (and LLMs) love