Lecture 2.1.4 Application of Stacks
Lecture 2.1.4 Application of Stacks
2
Reversing a
List
• A list of numbers can be reversed by reading each number from an
array starting from the first index and pushing it on a stack.
• Once all the numbers have been read, the numbers can be popped
one at a time and then stored in the array starting from the first
index.
3
Implementing Parentheses Checker
• Stacks can be used to check the validity of parentheses in
any algebraic expression.
• For example, an algebraic expression is valid if for every open
bracket there is a corresponding closing bracket.
• For example, the expression (A+B} is invalid but an expression {A + (B
– C)} is valid.
4
Evaluation of Arithmetic
Expressions
• The way to write arithmetic expression is known as a notation. An
arithmetic expression can be written in three different but equivalent
notations, i.e., without changing the essence or output of an
expression. These notations are −
1. Infix Notation
2. Prefix (Polish) Notation
3. Postfix (Reverse-Polish) Notation
5
Infix
Notation
• We write expression in infix notation, e.g. a - b + c, where operators
are used in-between operands.
• It is easy for us humans to read, write, and speak in infix notation but
the same does not go well with computing devices.
• An algorithm to process infix notation could be difficult and costly
in terms of time and space consumption.
6
Prefix
Notation
• In this notation, operator is prefixed to operands, i.e. operator is
written ahead of operands.
• For example, +ab. This is equivalent to its infix notation a + b.
• Prefix notation is also known as Polish Notation.
7
Postfix
Notation
• This notation style is known as Reversed Polish Notation.
• In this notation style, the operator is post fixed to the operands
i.e., the operator is written after the operands.
• For example, ab+. This is equivalent to its infix notation a + b.
8
Show the difference in all three notations
Sr.No. Infix Notation Prefix Notation Postfix Notation
1 a+b +ab ab+
2 (a + b) ∗ c ∗+abc ab+c∗
3 a ∗ (b + c) ∗a+bc abc+∗
4 a/b+c/d +/ab/cd ab/cd/+
5 (a + b) ∗ (c + d) ∗+ab+cd ab+cd+∗
6 ((a + b) ∗ c) - d -∗+abcd ab+c∗d-
9
Conversion of an Infix Expression into a
Postfix Expression
• infix notation may contain Sr.N Operator Precedence Associativity
o.
parentheses, operands, and
operators. 1 Exponentiation ^ Highest Right
Associative
• For simplicity of the algorithm 2 Multiplication ( ∗ Second Left
we will use only +, –, *, /, % ) & Division ( / )
Highest
Associative
operators.
3 Addition ( + ) & Lowest Left
Subtraction ( − ) Associative
10
Algorithm to convert an infix notation to postfix
notation
• The algorithm accepts an infix expression that may
contain operators, operands, and parentheses.
• For simplicity, we assume that the infix
operation contains only modulus (%),
multiplication (*), division (/), addition (+), and
subtraction (―) operators and that operators with
same precedence are performed from left-to-right.
• The algorithm uses a stack to temporarily hold
operators.
• The postfix expression is obtained from left-to-
right using the operands from the infix expression
and the operators which are removed from the
stack.
• The first step in this algorithm is to push a left
parenthesis on the stack and to add a
corresponding right parenthesis at the end of the
infix expression.
• The algorithm is repeated until the stack is empty
11
Consider the following Infix Expression ( A + B ) * ( C
-D)
12
13
Poll
Question
The postfix form of the expression (A+ B)*(C*D- E)*F / G is?
14
Infix to Postfix Conversion Example (Using Stack)
A/B^C-D
Current C-D B / AB Print Operand
Expression Symbol Stack Output Comment
Initially
Initial Stack
A/B^C-D NULL –
is
State Empty
Push Operator Onto
Stack because
Print Priority of ^ is
/B^C-D A NULL A Operand C-D ^ /^ AB greater than Current
Topmost Symbol of
Stack i.e ‘/’
Push
B^C-D / / A Operator
Onto Stack
Print
^C-D B / AB Operand -D C /^ ABC Print Operand
15
Step 1 : Now ‘^’ Has
Higher Priority than
Incoming Operator Step 1 : Now
So We have to Pop Stack Becomes
Topmost Element . Empty and
D – / ABC^ D – – ABC^/ We can Push
Step 2 : Remove
Topmost Operator Operand Onto
From Stack and Print Stack
it
16
Evaluation of a Postfix
Expression
• The ease of evaluation acts as the driving
force for computers to translate an infix
notation into a postfix notation.
• If the character encountered is an
operand, it is pushed on to the stack.
• However, if an operator is encountered,
• That is, given an algebraic expression then the top two values are popped from
written in infix notation, the computer the stack and the operator is applied on
first converts the expression into the these values. The result is then pushed on
equivalent postfix notation and then to the stack.
evaluates the postfix expression.
• Both these tasks—converting the infix
notation into postfix notation and
evaluating the postfix expression—make
extensive use of stacks as the primary
tool.
• Using stacks, any postfix expression can
be evaluated very easily.
• Every character of the postfix expression
is scanned from left to right.
17
Algorithm to evaluate a postfix
expression
18
Postfix Expression Evaluation using Stack
Data Structure
A postfix expression can be evaluated using the Stack data structure. To
evaluate a postfix expression using Stack data structure we can use the
following steps...
1. Read all the symbols one by one from left to right in the given Postfix
Expression
2. If the reading symbol is operand, then push it on to the Stack.
3. If the reading symbol is operator (+ , - , * , / etc.,), then perform TWO
pop operations and store the two popped oparands in two different
variables (operand1 and operand2). Then perform reading symbol
operation using operand1 and operand2 and push result back on to the
Stack.
4. Finally! perform a pop operation and display the popped value as final
result
19
Poll
Question
The prefix form of A-B/ (C * D ⋀ E) is?
a) -/*⋀ACBDE
b) -ABCD*⋀DE
c) -A/B*C⋀DE
d) -A/BC*⋀DE
20
Poll
Question
User push 1 element in the stack having already five elements and
having stack size as 5 then stack becomes .
1. Overflow
2. User Flow
3. Underflow
4. Crash
21
Exampl
e
22
23
Evaluation of a postfix
expression
Consider the infix expression given
as 9 – ((3 * 4) + 8) / 4. Evaluate the
expression.
The infix expression
9 – ((3 * 4) + 8) / 4
can be written as
934*8+4/–
using postfix notation.
24
Poll
Question
The type of expression in which operator succeeds its operands is?
a) Infix Expression
b) pre fix Expression
c) postfix Expression
d) None
25
Solve
Question
The result of evaluating the postfix expression
5, 4, 6, +, *, 4, 9, 3, /, +, *
26
Conversion of an Infix Expression into a Prefix
Expression
Step 1. Push “)” onto STACK, and add “(“ to Step 6. If left parenthesis is encontered
end of the A then
Step 2. Scan A from right to left and repeat a. Repeatedly pop from the STACK and add
to B (each operator on top of stack until
step 3 to 6 for each element of A until the a left parenthesis is encounterd)
STACK is empty b. b. Remove the left parenthesis
Step 3. If an operand is encountered add it Step 7. Exit
to B
Step 4. If a right parenthesis is
encountered
push it onto STACK
Step 5. If an operator is encountered then
a. Repeatedly pop from STACK and add to B
each operator (on the top of STACK)
which has same or higher precedence
than the operator.
b. b. Add operator to STACK
27
Infix to prefix
conversion
• Expression = (A+B^C)*D+E^5
Step 1. Reverse the infix expression.
5^E+D*)C^B+A(
Step 2. Make Every '(' as ')' and every ')' as '('
5^E+D*(C^B+A)
Step 3. Convert expression to postfix form.
A+(B*C-(D/E-F)*G)*H
28
Conversion of an Infix Expression into a Prefix
Expression
Expression Stack Output Comment
5^E+D*(C^B+A) Empty - Initial
^E+D*(C^B+A) Empty 5 Print
E+D*(C^B+A) ^ 5 Push
+D*(C^B+A) ^ 5E Push
D*(C^B+A) + 5E^ Pop And Push
*(C^B+A) + 5E^D Print
(C^B+A) +* 5E^D Push
29
C^B+A) +*( 5E^D Push
^B+A) +*( 5E^DC Print
B+A) +*(^ 5E^DC Push
+A) +*(^ 5E^DCB Print
A) +*(+ 5E^DCB^ Pop And Push
) +*(+ 5E^DCB^A Print
End +* 5E^DCB^A+ Pop Until '('
End Empty 5E^DCB^A+*+ Pop Every element
30
Solve
Question
Infix Expression : A + ( B * C - ( D / E ^ F ) * G ) * H
31
Solutio
n• Infix Expression : A + ( B * C - ( D / E ^ F ) * G ) * H
• Reverse the infix expression :
H*)G*)F^E/D(-C*B(+A
• Make Every “ ( ” as “ ) ” and every “ ) ” as “ ( ”
H*(G*(F^E/D)-C*B)+A
32
Convert expression to postfix
formScanned
: Stack Postfix Expression Description
( Start
H ( H
* (* H
( (*( H
G (*( HG
* (*(* HG
( (*(*( HG
F (*(*( HGF
^ (*(*(^ HGF
E (*(*(^ HGFE
' ^ ' is at highest
/ (*(*(/ HGFE^ precedence then ' / '
33
D (*(*(/ HGFE^D
) (*(* HGFE^D/
- (*(- HGFE^D/∗
C (*(- HGFE^D/∗C
* (*(-* HGFE^D/∗C
B (*(-* HGFE^D/∗CB
A (+ HGFE^D/∗CB∗-∗A
34
Poll
Question
Which of the following is not an inherent application of stack?
a) Reversing a string
b) Evaluation of postfix expression
c) Implementation of recursion
d) Job scheduling
35
Poll
Question
The prefix form of an infix expression p + q - r * t is ?
a) + pq - *rt
b) - +pqr * t
c) - +pq * rt
d) - + * pqrt
36
Poll
Question
Conversion of infix arithmetic expression to postfix expression uses.
A. Queue
B. Linked List
C. Circular queue
D. Stack
37
Algorithm for evaluation of a prefix
expression
38
Evaluation of a Prefix
Expression
• For example, consider the prefix expression + – 9 2 7 * 8 / 4 12.
39
Recursio
•nA recursive function is defined as a function that calls itself to solve a
smaller version of its task until a final call is made which does not
require a call to itself.
• Since a recursive function repeatedly calls itself, it makes use of the
system stack to temporarily store the return address and local
variables of the calling function.
• Every recursive solution has two major cases.
1. Base case, in which the problem is simple enough to be solved directly
without making any further calls to the same function.
2. Recursive case, in which first the problem at hand is divided into simpler
sub-parts. Second the function calls itself but with sub-parts of the problem
obtained in the first step. Third, the result is obtained by combining the
solutions of simpler sub-parts.
40
Types of
Recursion
1. Direct Recursion A function is said to be directly recursiveif it explicitly
calls itself.
2. Indirect Recursion A function is said to be indirectly recursive if it
contains a call to another function which ultimately calls it.
3. Tail Recursion A recursive function is said to be tail recursive if no
operations are pending to be performed when the recursive function
returns to its caller. when the called function returns, the returned value
is immediately returned from the calling function. Tail recursive functions
are highly desirable because they are much more efficient to use as the
amount of information that has to be stored on the system stack is
independent of the number of recursive calls.
41
Tower of
Hanoi
• The tower of Hanoi is one of the main applications of recursion.
• The Tower of Hanoi (also called the Tower of Brahma or Lucas'
Tower and sometimes pluralized as Towers) is a mathematical
game or puzzle.
• It consists of three rods and a number of disks of different sizes,
which can slide onto any rod.
• The puzzle starts with the disks in a neat stack in ascending order of
size on one rod, the smallest at the top, thus making a conical shape.
42
The objective of the puzzle is to move the entire stack to another rod,
obeying the following simple rules:
1. Only one disk can be moved at a time.
2. Each move consists of taking the upper disk from one of the stacks and
placing it on top of another stack i.e. a disk can only be moved if it is
the uppermost disk on a stack.
3. No disk may be placed on top of a smaller disk.
43
Take an example for 2
•disks
Take an example for 2 disks :
• Let rod 1 = 'A', rod 2 = 'B', rod 3 = 'C'.
44
45
QUICK
SORT
• Quicksort is an algorithm based on divide and conquer approach in which
the array is split into subarrays and these sub-arrays are recursively called
to sort the elements.
• quick sort is capable of sorting a list of data elements significantly faster
(twice or thrice faster) than any of the common sorting algorithms.
• It is one of the most efficient sorting algorithms and is based on the
splitting of an array (partition) into smaller ones and swapping (exchange)
based on the comparison with 'pivot' element selected.
• Due to this, quick sort is also called as "Partition Exchange" sort.
• Like Merge sort, Quick sort also falls into the category of divide and
conquer approach of problem-solving methodology.
46
The quick sort algorithm works as
follows:
1. Select an element pivot from the array elements.
2. Rearrange the elements in the array in such a way that all elements
that are less than the pivot appear before the pivot and all
elements greater than the pivot element come after it (equal values
can go either way). After such a partitioning, the pivot is placed in
its final position. This is called the partition operation.
3. Recursively sort the two sub-arrays thus obtained. (One with sub-
list of values smaller than that of the pivot element and the other
having higher value elements.)
47
Algorithm
for quick
sort
48
Example: Sort the elements given in the following array using quick sort
algorithm
49
50
Complexity of Quick
Sort
• In the average case, the running time of quick sort can be given as O(n log n). The
partitioning of the array which simply loops over the elements of the array once
uses O(n) time.
• In the best case, every time we partition the array, we divide the list into two
nearly equal pieces. That is, the recursive call processes the sub-array of half the
size. At the most, only log n nested calls can be made before we reach a sub-array
of size 1. It means the depth of the call tree is O(log n). And because at each level,
there can only be O(n), the resultant time is given as O(n log n) time.
• Practically, the efficiency of quick sort depends on the element which is chosen as
the pivot. Its worst-case efficiency is given as O(n2 ). The worst case occurs when
the array is already sorted (either in ascending or descending order) and the left-
most element is chosen as the pivot.
• However, many implementations randomly choose the pivot element. The
randomized version of the quick sort algorithm always has an algorithmic
complexity of O(n log n).
51
Pros and Cons of Quick
Sort
• It is faster than other algorithms such as bubble sort, selection sort,
and insertion sort. Quick sort can be used to sort arrays of small size,
medium size, or large size. On the flip side, quick sort is complex and
massively recursive.
52
REFERENCES
• Lipschutz, Seymour, “Data Structures”, Schaum's Outline Series, Tata McGraw Hill.
• Goodrich, Michael T., Tamassia, Roberto, and Mount, David M., “Data Structures and Algorithms in C++”, Wiley Student
Edition.
• https://www.tutorialspoint.com/data_structures_algorithms/algorithms_basics.htm
• https://www.cs.utexas.edu/users/djimenez/utsa/cs1723/lecture2.html
• Lipschutz, Seymour, “Data Structures”, Schaum's Outline Series, Tata McGraw Hill.
• Lipschutz, Seymour, “Data Structures”, Schaum's Outline Series, Tata McGraw Hill.
• Gilberg/Forouzan,” Data Structure with C ,Cengage Learning.
• Augenstein,Moshe J , Tanenbaum, Aaron M, “Data Structures using C and C++”, Prentice Hall of India
53
THANK
YOU
For queries
Email:
[email protected]