Site icon Study Algorithms

Write an Algorithm to convert an INFIX expression to a POSTFIX expression?

In infix expressions, the operator precedence is implicit unless we use parentheses. Therefore, for the infix to postfix conversion algorithm, we have to define the operator precedence inside the algorithm. We did this in the post covering infix, postfix and prefix expressions.

Important properties:-

THE ALGORITHM:-

  1. Create a stack
  2. for each character ‘t’ in the input stream {
    • if (t is an operand)
      output t
    • else if (t is a right parentheses){
      POP and output tokens until a left parentheses is popped(but do not output)
      }
    • else {
      POP and output tokens until one of lower priority than t is encountered or a left parentheses is encountered
      or the stack is empty
      PUSH t
      }
  3. POP and output tokens until the stack is empty.

For better understanding, let us trace out an example A * B – (C + D) + E

INPUT CHARACTER OPERATION ON STACK STACK POSTFIX EXPRESSION
A Empty A
* Push * A
B * A B
Check and Push A B *
( Push – ( A B *
C – ( A B * C
+ Check and Push – ( + A B * C
D – ( + A B * C D
) Pop and append to postfix till ‘(‘ A B * C D +
+ Check and push + A B * C D + –
E + A B * C D + – E
End of Input Pop till Empty Empty A B * C D + – E +

So our final POSTFIX Expression :- A B * C D + – E +

Exit mobile version