This project is about sorting a stack A by ascending order with two stacks with a limited number of operations available. The only possible operations are the following:
- sa (swap a): Swap the first 2 elements at the top of stack a. Do nothing if there is only one or no elements.
- sb (swap b): Swap the first 2 elements at the top of stack b. Do nothing if there is only one or no elements.
- ss : sa and sb at the same time.
- pa (push a): Take the first element at the top of b and put it at the top of a. Do nothing if b is empty.
- pb (push b): Take the first element at the top of a and put it at the top of b. Do nothing if a is empty.
- ra (rotate a): Shift up all elements of stack a by 1. The first element becomes the last one.
- rb (rotate b): Shift up all elements of stack b by 1. The first element becomes the last one.
- rr : ra and rb at the same time.
- rra (reverse rotate a): Shift down all elements of stack a by 1. The last element becomes the first one.
- rrb (reverse rotate b): Shift down all elements of stack b by 1. The last element becomes the first one.
- rrr : rra and rrb at the same time.
The full subject can be found here.
- The algorithm is looping through all the elements and calculate the cost to move it to the correct position in stack B (in descending order). It then moves the cheapest element.
- Once only three elements remain in stack A, they are sorted with a custom function.
- We then loop through stack B to again find the cheapest element to move.
- Once everything is done we rotate stack A until the smallest element is on top and the stack is sorted
Clone the repository and use make
to compile
git clone https://github.com/theozanchi/42_Berlin_Push_swap/tree/main
cd 42_Berlin_Push_swap
make
The Push_swap visualizer developped by o-reo can be used how the algorithm works.