Professional Documents
Culture Documents
Evaluation of Postfix Expression
Evaluation of Postfix Expression
Recursive Function:
OS process: Stack, Queue, Priority Queue
Compiler task: Algebric expression
Recursive Fn:
N! = 1*2…*(n-2)*(n-1)*n
Factorial(n)
{Fact=n*Factorial(n-1)
-
-
Return}
Fact(n)->fact(n-1)->fact(n-2)……..fact(2)->fact(1)=1
A+{B*C-(D/E^F)* G}*H
Alogorithm 6.5
1. Add a right parenthesis “)” at the end of the P
2. Scan P from left to right and repeat steps 3,4 for each element of P until senitel “)” is
encountered
3. If an operand is encountered, put it on Stack
4. If an OPERATOR is encountered then:
a. Remove the two top elements of stack where A is top and B is next to top
b. Evaluate B OPERATOR A
c. Place the result of (b) back on Stack
[End of Step 2 loop]
5. Set VALUE equal to top element of Stack
6. exit
Stack Postfix, P
(+( ABC*
(+(- ABC*DEF
(+(-* ABC*DEF^/G
ABC*DEF^/G*-H*+
Prefix to Postfix:
Infix Q: A+(B*C-(D/E^F)*G)*H)
Postfix, P: A B C * DEF^/G*- H * +
Algorithm 6.6 Polish(Q,P)
1. Push “(“ onto Stack and “)” to the end of Q
2. Scan Q from left to right and repeat steps 3 to 6 for each element of Q:
3. If an operand is encountered, add it to P
4. If left parenthesis is encountered, push onto stack
5. If and operator is encountered then:
a. Repeatedly pop from Stack and add to P each operator with same or higher precedence
than operator
b. Add operator to Stack
6. If a right parenthesis is encountered then:
a. Repetedly pop from stack and add it to P each operator until a left parenthesis is
encountered
b. Remove left parenthesis from Stack
[End of step 2 loop]
7. Exit
Sorting:
Numeric value
Alphabetic/Alphaneumeric
659 388
3 5 6 8 8 9 Ascending Asc
9 8 8 6 5 3 Descending Desc
Bubble Sort
Selection
Insertion Sort
Merge sort
Quicksort
Bucket sort
Counting
Nested Loop:
Algorithm 4.4 Bubble(Data, N)
1. Repeat steps 2 and 3 for K=1 to N-1
2. Set PTR=1 [Initialize pass pointer]
3. Repeat while PTR<=N-K
a. If DATA[PTR]>Data[PTR+1] then
Interchange DATA[PTR] and Data[PTR+1]
b. Set PTR=PTR+1
[End of loop]
Bubble Sort: K= 1 to 7 PTR= 1 to N-K Temp=13 ptr=1 to 6
1 2 3 4 5 6 7 8=N
13 23 27 85 66 51 32 57
13 23 27 66 51 32 57 85 K=1
13 23 27 51 32 57 66 85 K=2
13 23 27 32 51 57 66 85 K=3
K=4
K=7
K= 1
PTR=1 DATA[1]>Data[2] 13>23
PTR=2 DATA[2]>Data[3] 23>27
PTR=3 DATA[3]>Data[4] 27>85
PTR=4 DATA[4]>Data[5] 85>66 true swap
PTR=5 DATA[5]>Data[6] 85 > 51 true swap
PTR=6 DATA[6]>Data[7] 85>32 true swap
PTR=7 DATA[7]>Data[8] 85>57 true swap
PTR= 8-2=6
PTR=1 DATA[1]>Data[2]
PTR=2 DATA[2]>Data[3]
PTR=3 DATA[3]>Data[4]
PTR=4 DATA[4]>Data[5]
PTR=5 DATA[5]>Data[6]
PTR=6 DATA[6]>Data[7]
For (k 1 to N-1)
For ( j 1 to N-k)
If(Data[j]>Data[J+1]
Temp=Data[j]
Data[j]= Data[j+1]
Data[j+1]= temp
1 index 2 3 index 4 5 6 index 7 index 8=N
32 51 27 85 66 23 13 57
13 51 27 85 66 23 32 57 i=1
13 23 27 85 66 51 32 57 I=2
13 23 27 85 66 51 32 57 i=3
13 23 27 32 66 51 85 57 I=4
13 23 27 32 51 57 66 85 I=5