The purpose of this project is sort data on a stack, with specific rules, using the lowest possible number of actions.
The push_swap
program takes a set of int
values, sorts the values using rules and writes commands that make the set sorted. To do this, you need think the algorithm and implement it.
We have 2 stacks named a
and b
. To start with:
a
- contains a random number of either positive or negative numbers without any duplicatesb
- is empty
The goal is to sort in ascending order numbers into stack a
.
To do this we have the following commands at your disposal:
sa
- swap a swap the first 2 elements at the top of stacka
. Do nothing if there is only one or no elementssb
- swap b swap the first 2 elements at the top of stackb
. Do nothing if there is only one or no elementsss
- swap a and swap b at the same timepa
- push a - take the first element at the top ofb
and put it at the top ofa
. Do nothing ifb
is emptypb
- push b - take the first element at the top ofa
and put it at the top ofb
. Do nothing ifa
is emptyra
- rotate a - shift up all elements of stacka
by 1. The first element becomes the last onerb
- rotate b - shift up all elements of stackb
by 1. The first element becomes the last onerr
- rotate a and rotate b at the same timerra
- reverse rotate a - shift down all elements of stacka
by 1. The last element becomes the first onerrb
- reverse rotate b - shift down all elements of stackb
by 1. The last element becomes the first onerrr
- reverse rotate a and reverse rotate b at the same time
Input parameters and output of the implemented programme:
$> ./push_swap 2 1 3 6 5 8
sa
pb
pb
pb
sa
pa
pa
pa
To complete the project, I used next algoritm.
But to perfectly works, I had to make some additions.
If you are sure that the algorithm works perfectly, you can proceed to the bonus. You need to write your own checker
, repeating the behaviour of the standard checker_OS
.
Input parameters and output of the implemented programme:
$> ./checker 2 1 3 6 5 8
sa
pb
pb
pb
sa
pa
pa
pa
OK