Introduction
Push Swap solves the sorting problem using two stacks (A and B) and a limited set of operations. The algorithm adapts its strategy based on the size of the input, using different approaches for small and large stacks to minimize the number of operations.Two-Stack Mechanism
The algorithm operates with two stacks:- Stack A: Contains the initial unsorted numbers and will hold the final sorted result
- Stack B: Used as auxiliary storage during the sorting process
Available Operations
The algorithm can only use these stack operations:sa,sb,ss: Swap the first two elementspa,pb: Push from one stack to anotherra,rb,rr: Rotate (shift up)rra,rrb,rrr: Reverse rotate (shift down)
Sorting Strategies by Size
The algorithm selects different strategies based on stack size, as implemented inpush_swap.c:59:
Size 2: Direct Swap
For two elements, the algorithm simply usessa to swap if needed. This is the optimal solution requiring at most 1 operation.
Size 3: Hardcoded Solution
For three elements,sort_three() uses a hardcoded decision tree that handles all 6 possible permutations. Each case is solved with the minimal number of operations (0-2 operations).
View sort_three() implementation
View sort_three() implementation
push_swap.c
Size 4+: Turkish Algorithm
For larger stacks, the algorithm uses the Turkish (Turk) algorithm, which is a greedy cost-based approach. This is implemented insort_big_stacks() and is detailed in the Turkish Algorithm page.
High-Level Flow
Check if sorted
Before starting, the algorithm checks if the stack is already sorted using
is_stack_sorted(). If sorted, no operations are performed.Select strategy
Based on the stack size, the appropriate sorting function is called:
- 2 elements →
sa - 3 elements →
sort_three() - 4+ elements →
sort_big_stacks()
Execute sorting
The selected strategy performs the sorting operations, outputting each operation to stdout.
Optimization Philosophy
The algorithm prioritizes:- Operation count: Minimizing the total number of operations
- Efficiency: Using combined operations (
rr,rrr,ss) when both stacks need the same action - Greedy approach: Always selecting the cheapest move for large stacks
- Median awareness: Choosing rotate vs reverse rotate based on element position
The algorithm always leaves Stack A sorted in ascending order with the smallest element at the top.
Next Steps
Turkish Algorithm
Deep dive into the cost-based sorting strategy for large stacks
Complexity Analysis
Understand time and space complexity of the algorithm