This project will make you sort data on a stack, with a limited set of instructions, using the lowest possible number of actions.
To succeed you’ll have to manipulate various types of algorithms and choose the most appropriate solution (out of many) for an optimized data sorting.
push_swap
program should sort the integers received as arguments using the lowest possible number of instruction and display these instruction on the standart output.
• You have 2 stacks named a and b.
• At the beginning:
◦ The stack a contains a random amount of negative and/or positive numbers which cannot be duplicated.
◦ The stack b is empty.
• The goal is to sort in ascending order numbers into stack a. To do so you have the
🔁 Allowed operations 🔁:
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.
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.
To sort three elements I hard coded saveral cases.
For example:
Case 1
1 | 5 | 1 | ||
5 | sa | 1 | ra ↑ | 3 |
3 | 3 | 5 |
Case 2
3 | 1 | |
1 | sa | 3 |
5 | 5 |
Case 3
3 | 1 | |
5 | rra ↓ | 3 |
1 | 5 |
Case 4
5 | 3 | 1 | ||
3 | ra ↑ | 1 | sa | 3 |
1 | 5 | 5 |
Case 5
5 | 1 | |
1 | ra ↑ | 3 |
3 | 5 |
For more than three elements and less than ten I used this algorithm ->
For number of elements more than 10 I used algo where we should count the number of moves for every element in stack b and choose the "cheapest" element to push to spack a.
It is really helpfull to try this algo in Google Docs to visualize its realization.
School21 algo explanations
For bonus part we need to make checker
program that should test whether push_swap
sort stack properly.
make
or make all
will compile both push_swap and checker programs
./push_swap [list of arguments]
ARG="[list of arguments]"; ./push_swap $ARG | ./checker $ARG
ARG=`ruby -e "puts (1..500).to_a.shuffle.join(' ')"`; ./push_swap $ARG | ./checker $ARG
ARG="-755254759 46382822 168313279 -712408378 -976005565 532734670 -658929270"; ./push_swap $ARG