ceng2001_week3
ceng2001_week3
))))((((
()))
(()()(()
The program challenge
• write an algorithm that will read a string of
parentheses from left to right and decide
whether the symbols are balance.
• See code
• Time complexity: 𝑂(𝑛)
• Space complexity: 𝑂(𝑛)
Stack for converting decimal to binary
• Binary is especially important to CS and
programming since the computer stores
everything in binary one and zeros:
• 110101100011
• Hex is another base that is easier then binary
but each hex digit represents 4 bits
– Hex uses the digits 0123456789ABCDEF
• 1101 0110 0011 would be D63
Stack for converting decimal to binary
• The decimal number 23310 and its
corresponding binary equivalent 111010012
are interpreted respectively as
2×102+3×101+3×100
and
1×27+1×26+1×25+0×24+1×23+0×22+0×21+1×20
Easy divide by 2 and collect
Decimal: 233
remainders
20 digit
See code
• Time complexity: 𝑂(logb 𝑛)
• Space complexity: 𝑂(logb 𝑛)
inFix, prefix, postfix and
evaluation
infix
• when you write an expression
C*D
• you know form the form that you multiply the
value of variable C by the value in variable D
• This type of notation is know as infix since the
operator * is in between the two operators C
and D
more infix
• consider
B+C*D
• this is more complicated, which do you do
first, B + C or C * D
• Well you know because you have been doing
this that the order of precedence tells you
when what to do first. The only exception to
precedence is adding ( )
Fully Parenthesized
• If you add a pair of parentheses around every
operation in a way to indicate the order needed
B+C*D becomes (B+(C*D))
( A + ( B * C ) )
( A + ( B * C ) )
1 --------2--------
( A + ( B * C ) )
( A + ( B C * ) )
Algorithm to convert infix to postfix
• when you fully parenthesize an expression
every pair of parentheses denotes two
operands with an operator in the middle
( A + ( B C * ) )
1 --------2--------
( A ( B C * ) + )
1 --------2--------
A B C * +
take out extra spaces:
A B C * +
• You do prefix by just moving operator to left,
but other wise it is the same:
The algorithm
• we will be evaluating converting a infix
expression (not fully parenthesized) to postfix
• We will design a function named
infixToPostfix( string parameter)
that return a new string expression in postfix.
The string expression must have a space
between every token of ( ) a number of
operator
Algorithm
• Consider
( A + B ) * C -> becomes A B + C *
when we see ( we know that what is in the () is high
precedence and can be done when we see the
matching ) pair -> A B +
• But for the expression A + B * C the result is:
A B C * +, we need to reverse the operators when
the precedence dictates it. since reversal is nicely
handled with a stack, that is what we will use
Algorithm