News


Algorithm for Infix to Postfix

One of the applications of stack is in the evaluation of arithmetic expressions. To evaluate any arithmetic expression we convert the infix expression to postfix. Then evaluate the postfix expression using a stack. In this article I would define the standard algorithm for this.

Define a stack
Go through each character in the string
If it is between 0 to 9, append it to output string.
If it is left brace push to stack
If it is operator *+-/ then
          If the stack is empty push it to the stack
          If the stack is not empty then start a loop:
                             If the top of the stack has higher precedence
                             Then pop and append to output string
                             Else break
                     Push to the stack

If it is right brace then
            While stack not empty and top not equal to left brace
            Pop from stack and append to output string
            Finally pop out the left brace.

If there is any input in the stack pop and append to the output string.

Here is the code for conversion from infix to postfix.

public static string ConvertInfixToPostfix(string infix)

{

    int length = infix.Length;

    Stack<char> stack = new Stack<char>();

    StringBuilder postfix = new StringBuilder();

 

    for (int i = 0; i < length; i++)

    {

        if ((infix[i] >= '0') && (infix[i] <= '9'))

        {

            postfix.Append(infix[i]);

        }

        else if (infix[i] == '(')

        {

            stack.Push(infix[i]);

        }

        else if ((infix[i] == '*') || (infix[i] == '+') || (infix[i] == '-') || (infix[i] == '/'))

        {

            while ((stack.Count > 0) && (stack.Peek() != '('))

            {

                if (ComparePrecedence(stack.Peek(), infix[i]))

                {

                    postfix.Append(stack.Pop());

                }

                else

                {

                    break;

                }

            }

            stack.Push(infix[i]);

        }

        else if (infix[i] == ')')

        {

            while ((stack.Count > 0) && (stack.Peek() != '('))

            {

                postfix.Append(stack.Pop());

            }

            if (stack.Count > 0)

                stack.Pop(); // popping out the left brace '('

        }

        else

        {

        }

    }

    while (stack.Count > 0)

    {

        postfix.Append(stack.Pop());

    }

    return postfix.ToString();

}

 

private static bool ComparePrecedence(char top, char p_2)

{

    if (top == '+' && p_2 == '*') // + has lower precedence than *

        return false;

 

    if (top == '*' && p_2 == '-') // * has higher precedence over -

        return true;

 

    if (top == '+' && p_2 == '-') // + has same precedence over +

        return true;

 

    return true;

}

 

public static int EvaluatePostFix(string postfix)

{

    Stack<int> resultStack = new Stack<int>();

    int length = postfix.Length;

    for (int i = 0; i < length; i++)

    {

        if ((postfix[i] == '*') || (postfix[i] == '+') || (postfix[i] == '-') || (postfix[i] == ''))

        {

            int result = ApplyOperator(resultStack.Pop(), resultStack.Pop(), postfix[i]);

            resultStack.Push(result);

        }

        else if ((postfix[i] >= '0') || (postfix[i] <= '9'))

        {

            resultStack.Push((int)(postfix[i] - '0'));

        }

        else

        {

        }

    }

    return resultStack.Pop();

}

 

private static int ApplyOperator(int p, int p_2, char p_3)

{

    switch (p_3)

    {

        case '+':

            return p_2 + p;

        case '-':

            return p_2 - p;

        case '*':

            return p_2 * p;

        case '/':

            return p_2 / p;

        default:

            return -1;

    }

    return -1;

}

 

 


Comments

Gravatar # re: Algorithm for Infix to Postfix
Posted by soofi on 12/1/2010 4:02 AM
i have a project similar to this, i am just wondring can you help me. i have a problem?
Gravatar # re: Algorithm for Infix to Postfix
Posted by wyeth on 2/2/2011 1:27 PM
hi.. can you give me a correct program in converting infix expression to postfix expression using string?? example is. infix: 1+2----> postfix: 12+..
thanks
Gravatar # re: Algorithm for Infix to Postfix
Posted by Wesam .Nm on 3/6/2011 2:59 PM
Is there an algorithm or a ideal code for infix to postfix
Can you publish a code to rewrite a polynomial in
postfix

Thank you (It's a very useful website)
Gravatar # re: Algorithm for Infix to Postfix
Posted by Nahid on 3/8/2011 1:36 AM
thank you for every thing
you solved all my problems
I love your site
Gravatar # re: Algorithm for Infix to Postfix
Posted by komal on 8/17/2011 10:06 PM
boosting up the knowledge.
Gravatar # re: Algorithm for Infix to Postfix
Posted by mary ann abaring on 9/1/2011 11:43 AM
nice..keep up the good work
Gravatar # re: Algorithm for Infix to Postfix
Posted by Mohammad walid on 11/2/2011 9:03 PM
thank you very much for your effort
Gravatar # re: Algorithm for Infix to Postfix
Posted by Shana on 11/10/2011 6:00 AM
Thanks so much! I was trying to understand my textbook version of this and it was NOT clear! Thanks for a really thorough explanation!
Gravatar # re: Algorithm for Infix to Postfix
Posted by vivek on 2/4/2012 10:40 AM
hi. can u give me a algo and program for infix to prefix in c without using pointer
Gravatar # re: Algorithm for Infix to Postfix
Posted by Troy on 3/18/2012 7:23 PM
Thank you very much for this gem.
Your algorithm as well as the java program guided me with my PHP version. Thank you!
Gravatar # re: Algorithm for Infix to Postfix
Posted by ranjith on 5/25/2012 1:39 AM
SUPER ALGORITHM
Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification: