Overview
Push operations move the top element from one stack to another. These operations are fundamental to the Push Swap algorithm, as they enable the distribution and consolidation of elements between stacks A and B during the sorting process.Available Operations
pa
Push the top element from stack B to stack A
pb
Push the top element from stack A to stack B
How It Works
A push operation removes the top element from the source stack and places it at the top of the destination stack:If the source stack is empty, the push operation does nothing.
Implementation
The push operations are implemented inft_push.c. Here’s the complete implementation:
Core Push Function
ft_push.c
- Validation: Check if the source stack is empty
- Extract: Save reference to the top node and update source stack head
- Update Source: Adjust the new top node’s
prevpointer to NULL - Insert into Destination:
- If destination is empty: Make the node the only element
- If destination has elements: Insert at the top and update links
Public Operation Functions
- pa
- pb
ft_push.c
a: Pointer to stack A (destination)b: Pointer to stack B (source)print: If false, outputs “pa” to stdout
Detailed Operation Flow
Pushing to an Empty Stack
Pushing to a Non-Empty Stack
Usage Examples
Example 1: Distributing Elements
Moving elements to stack B for processing:Example 2: Returning Elements
Bringing sorted elements back to stack A:Example 3: Empty Stack Handling
Common Patterns
Pattern 1: Partition Strategy
Pattern 2: Consolidation
Pattern 3: Selective Transfer
Strategic Use
Push operations are essential for:Divide and Conquer
Divide and Conquer
Splitting the input into manageable subsets by pushing elements between stacks based on criteria (e.g., value ranges, median comparisons).
Temporary Storage
Temporary Storage
Using stack B as a temporary holding area while organizing elements in stack A, then retrieving them in the optimal order.
Sorting Phases
Sorting Phases
Implementing multi-phase sorting where elements are pushed to B, sorted, and then pushed back to A in the correct order.
Cost Optimization
Cost Optimization
Moving elements that are expensive to sort in their current position to a better location for processing.
Performance Characteristics
- Time Complexity: O(1) - constant time operation
- Space Complexity: O(1) - no additional memory allocation
- Stack Modification: Changes the size of both stacks
See Also
Swap Operations
Exchange top two elements
Rotate Operations
Shift stack elements upward
Reverse Rotate
Shift stack elements downward