Answer the question
In order to leave comments, you need to log in
Sorting an array?
Greetings!
I ask for help from the respected Habra community with the solution of such a problem:
In the process of writing a simple interpreter of mathematical expressions (so far even without brackets, banal expressions like 5+15*2/10+2^3 ) just 4 fun, as they say, ran into a problem...
I get an array of operations in an expression of the form position=>operation, which for the above example would be:
array(
1 => '+',
4 => '*',
6 => '/'
9 => '+',
11 => '^',
)
array(
'+' => 1,
'-' => 1,
'*' => 2,
'/' => 2,
'^' => 3,
)
array(
11 => '^',
4 => '*',
6 => '/',
1 => '+',
9 => '+',
)
Answer the question
In order to leave comments, you need to log in
You have the wrong position initially. You need not to collect a linear array, but a tree of arguments and operators.
When viewing the expression, form an array of records where the value will be the structure of Priority and Operation. Further, by means of the language, sorting by the priority field should not be a problem (the usual passage of a function through an array).
In general, the ideal option is Reverse Polish notation .
I wrote a similar calculator, but with brackets. I asked myself such a test for a workshop when studying C. In my opinion, a bicycle is simpler than reverse Polish notation (it is also postfix) for such arithmetic has not yet been invented. Everything else is a complication, giving more confusion than effectiveness.
For fun - look towards the Fort language. All arithmetic is postfix :)
Who prevents the structure [Priority, Operation] from inserting Position as well? But why do you need her?
You need to parse the entered expression into a form convenient for processing by recursion or a loop.
I would aim for something like this (for 5+15*2/10+2^3):
array( 0 => '2^3', 1 => '2/10', 2 => '15*{1}', 3 => '5+{2}', 4 => '{3}+{0}, );
Make an array of operations with pre-known keys:
array(
'^' => array(),
'*' => array(),
'/' => array(),
'+' => array(),
'-' => array(),
);
Form
an array(
1 => 1,
4 => 2,
6 => 2,
9 => 1,
11 => 3,
)
and sort it?
In general, it is better to read Dragon Book, there is about it.
You can try using a priority queue (popularly referred to as a “heap”). In C++ it is called priority_queue, in java it is called PriorityQueue. You can organize each element of your array as a structure (or class) with two fields: position, operation. And overload the comparison operator (<) for the given class. Then, when parsing the expression, you will insert elements into this queue and they will be there in a sorted form. The complexity is equivalent to the complexity of sorting (insertion of each element will be done in O(log N), where N is the number of elements already in the queue).
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question