Professional Documents
Culture Documents
top
top E
D D D
C top C C C
B top B B B B
A A A A A
A top
Stack Applications
• Real life
– Pile of books
– Plate trays
• More applications related to computer science
• Parsing
• Recursive Function
• Calling Function
• Expression Evaluation
• Expression Conversion
– Infix to Postfix
– Infix to Prefix
– Postfix to Infix
– Prefix to Infix
• Towers of hanoi
Applications of Stacks
• Direct applications
– Page-visited history in a Web browser
– Undo sequence in a text editor
– Saving local variables when one function calls
another, and this one calls another, and so on.
• Indirect applications
– Auxiliary data structure for algorithms
– Component of other data structures
Array-based Stack Implementation
• Allocate an array of some size (pre-defined)
– Maximum N elements in stack
• Bottom stack element stored at element 0
• last index in the array is the top
• Increment top when one element is pushed,
decrement after pop
How to insert an ITEM
PUSH(STACK,TOP,MAXSTK,ITEM)
• This procedure pushes an ITEM onto a
sack
1.[Stack already filled ?]
If TOP=MAXSTK,then:
print:OVERFLOW, and Return.
2.Set TOP:=TOP+1[increase TOP by 1]
3.Set STACK[TOP]:=ITEM
[insert ITEM in new TOP position]
4.Return
How to remove an ITEM?
POP(STACK,TOP,ITEM)
This procedure deletes the top element of STACK
And assigns it to the variable ITEM.
abc{defg{ijk}{l{mn}}op}qr
– An example of unbalanced braces
abc{def}}{ghij{kl}m
abc{def}{ghij{kl}m
Checking for Balanced Braces
• Requirements for balanced braces
–Each time you encounter a “}”, it
matches an already encountered
“{”
–When you reach the end of the
string, you have matched each “{”
Checking for Balanced Braces
Answer: (C)
2) In evaluating the arithmetic expression 2 * 3-
(4+5), using stacks to evaluate its equivalent
post-fix form, which of the following stack
configuration is not possible?
A)4,6 b)5,4,6 C) 9,9 D)9,3,2
3) Stack A has the entries a, b, c (with a on top),
Stack B is empty. An entry popped out of stack A
can be printed immediately or pushed to stack
B. An entry popped out of stack B can only be
printed. In the arrangement, which of the
following permutations of a, b, c is not possible?
A)b,a,c B)b,c,a C)c,a,b D)a,b,c
• The evaluated value of POSTFIX EXPRESSION 4
3 * 4 2 / - 3 2 $ 2 * + is ………………
Example:- Apply quick sort 75, 70, 65, 68, 61, 55, 100, 93, 78, 98, 81,
84
QUICKSORT: an application of STACK
• Procedure 6.7: QUICK(A,N,BEG,END,LOC)
Here A is an array with N elements . parameters BEG and END contain the
boundary values of the sub list of A to which this procedure applies.LOC
keeps track of the position of the first element A[BEG] of the sub list during
the procedure . The local variable LEFT and RIGTH will contain the boundary
values of the list of elements that have not been scanned.
1.[Initialize] set LEFT:=BEG,RIGTH:=END and LOC:=BEG.
2.[scan from right to left.]
(a)Repeat while A[LOC]<= A[RIGHT] and
LOC ≠RIGHT:RIGHT:=RIGHT-1.
[End of loop]
(b) If LOC=RIGHT , then : Return.
(c)If A[LOC]>A[RIGTH],then:
I )[Interchange A[LOC] and A[RIGHT].
TEMP:=A[LOC],A[LOC]:=A[RIGHT],
A[RIGHT]:=TEMP.
QUICKSORT
II) Set LOC:=RIGHT.
III)Go to step 3.
[End of If structure.]
3.[scan from left to right]
(a)Repeat while A[LEFT]<=A[LOC] and LEFT != LOC:
LEFT:=LEFT+1.
[End of loop.]
(b)If LOC=LEFT , then : return.
(c)If A[LEFT]>A[LOC],then
I )[interchange A[LEFT] and A[LOC].
TEMP:=A[LOC], A[LOC]:=A[LEFT],A[LEFT]:=TEMP.
II)set LOC:=LEFT.
III)Go to step 2.
[End of If structure.]
Algorithm 6.8: (Quicksort)
• This algorithm sorts an array A with N Elements
1.[Initialize] TOP:=NULL.
2.[Push boundary values of A onto stacks when A has
two or more elements.]
If N>1,then:TOP:=TOP+1,LOWER[1]:=1,UPPER[1]:=N.
3.Repeat step 4 to 7 While TOP =/= NULL.
4. [pop sublist from stacks]
Set BEG:=LOWER[TOP],END:=UPPER[TOP],
TOP:=TOP-1.
5. Call QUICK(A,N,BEG,END,LOC).
[procedure QUICK]
Algorithm 6.8: (Quicksort)
6.[push left sublist onto stacks when it has 2 or more
elements.]
IF BEG<LOC-1,then:
TOP:=TOP+1,LOWER[TOP]:=BEG,
UPPER[TOP]=LOC-1,
[end of if structure]
7.[push right sublist onto stacks when it has two or more
elements.]
If LOC+1< END,then:
TOP:=TOP+1,LOWER[TOP]:=LOC+1,
UPPER[TOP]:=END.
[end of if structure.]
[end of step 3 loop]
8.Exit.
Complexity of Quick sort algorithm
• Worst case complexity
• f(n)=n+(n-1)+(n-2)+---------------+2+1 =n(n+1)/2
=n2 / 2 + O(n)=O(n2).
• Average case Complexity
• f(n)=O(n log n)
On average each reduction step of the algorithm produces two
sublists.
1) Reducing the initial list places 1 element and produces 2 sublist.
2) Reducing the two sub list places 2 element and produces 4
sublist. And so on.
3) Reduction step in kth level finds the location of 2k-1 elements.
4) Approximately log2n levels of reduction steps.
5) Each level uses at most n comparisons, so f(n)=O(n log n)
Recursion
• What is recursion?
• Sometimes, the best way to solve a problem is
by solving a smaller version of the exact same
problem first
• Recursion is a technique that solves a problem
by solving a smaller problem of the same type
Recursion
• Some computer programming languages allow
a module or function to call itself. This
technique is known as recursion.
• In recursion, a function α either calls itself
directly or calls a function β that in turn calls
the original function α. The function α is
called recursive function
Recursion
• Properties
• A recursive function can go infinite like a loop. To
avoid infinite running of recursive function, there
are two properties that a recursive function must
have −
• Base criteria − There must be at least one base
criteria or condition, such that, when this
condition is met the function stops calling itself
recursively.
• Progressive approach − The recursive calls should
progress in such a way that each time a recursive
call is made it comes closer to the base criteria.
When you turn this into a program, you end up with
functions that call themselves (recursive functions)
int f(int x)
{
int y;
if(x==0)
return 1;
else {
y = 2 * f(x-1);
return y+1;
}
}
Problems defined recursively
• There are many problems whose solution can
be defined recursively
Example: n factorial
1 if n = 0
n!= (recursive solution)
(n-1)!*n if n > 0
1 if n = 0
n!= (closed form solution)
1*2*3*…*(n-1)*n if n > 0
Coding the factorial function
• Recursive implementation
int Factorial(int n)
{
if (n==0) // base case
return 1;
else
return n * Factorial(n-1);
}
Recursive Algorithms Computer
Implementation
long factorial(int n){
if (n<=0) return 1;
return n*factorial(n-1);
}
Compute 5!
L16 53
Recursive Algorithms Computer
Implementation
long factorial(int n){
if (n<=0) return 1;
return n*factorial(n-1);
}
f(5)=
5·f(4)
L16 54
Recursive Algorithms Computer
Implementation
long factorial(int n){
if (n<=0) return 1;
return n*factorial(n-1);
}
f(4)= f(5)=
4·f(3) 5·f(4)
L16 55
Recursive Algorithms Computer
Implementation
long factorial(int n){
if (n<=0) return 1;
return n*factorial(n-1);
}
L16 56
Recursive Algorithms Computer
Implementation
long factorial(int n){
if (n<=0) return 1;
return n*factorial(n-1);
}
L16 57
Recursive Algorithms Computer
Implementation
long factorial(int n){
if (n<=0) return 1;
return n*factorial(n-1);
}
L16 58
Recursive Algorithms Computer
Implementation
long factorial(int n){
if (n<=0) return 1;
return n*factorial(n-1);
}
L16 59
Recursive Algorithms Computer
Implementation
long factorial(int n){
if (n<=0) return 1;
return n*factorial(n-1);
}
L16 60
Recursive Algorithms Computer
Implementation
long factorial(int n){
if (n<=0) return 1;
return n*factorial(n-1);
}
L16 61
Recursive Algorithms Computer
Implementation
long factorial(int n){
if (n<=0) return 1;
return n*factorial(n-1);
}
4·6= f(5)=
24→ 5·f(4)
L16 62
Recursive Algorithms Computer
Implementation
long factorial(int n){
if (n<=0) return 1;
return n*factorial(n-1);
}
5·24=
120→
L16 63
Recursive Algorithms Computer
Implementation
long factorial(int n){
if (n<=0) return 1;
return n*factorial(n-1);
}
Return 5!
= 120
L16 64
Recursive Definition for Fibonacci
If n=0 or n=1, then Fn =n
int b(int x)
{
int z,y;
……………… // other statements
z = a(x) + y;
return z;
}
What happens when a function is called?
(cont.)
• An activation record is stored into a stack
(run-time stack)
1) The computer has to stop executing
function b and starts executing function a
2) Since it needs to come back to function b
later, it needs to store everything about
function b that is going to need (x, y, z,
and the place to start executing upon
return)
3) Then, x from a is bounded to w from b
4) Control is transferred to function a
What happens when a
function is called? (cont.)
• After function a is executed, the activation
record is popped out of the run-time stack
• All the old values of the parameters and
variables in function b are restored and the
return value of function a replaces a(x) in the
assignment statement
What happens when a recursive
function is called?
• Except the fact that the calling and called functions have the
same name, there is really no difference between recursive
and nonrecursive calls
int f(int x)
{
int y;
if(x==0)
return 1;
else {
y = 2 * f(x-1);
return y+1;
}
}
The Towers of Hanoi
A Stack-based Application
– GIVEN: three poles
– a set of discs on the first pole, discs of different sizes, the smallest
discs at the top
– GOAL: move all the discs from the left pole to the right one.
– CONDITIONS: only one disc may be moved at a time.
– A disc can be placed either on an empty pole or on top of a larger disc.
Towers of Hanoi
Towers of Hanoi
Towers of Hanoi
Towers of Hanoi
Towers of Hanoi
Towers of Hanoi
Towers of Hanoi
Towers of Hanoi
• For n>1 disc may be reduced to the following
sub problems
• Move top n-1 disc from peg A to Peg B
• Move the top disc from peg A to Peg C
• Move top n-1 disc from peg B to Peg C
• The solution may be reduced to the solution
of the following three sub problems
TOWER(N-1,BEG,END,AUX)
TOWER(1,BEG,AUX,END) OR BEG→END
TOWER(N-1, AUX, BEG,END)
Tower of Hanoi algorithm
• Procedure TOWER(N,BEG,AUX,END)
1.If N=1 then:
Write: BEG-> END.
Return.
[end of if structure]
2.Call TOWER(N-1,BEG,END,AUX)
3.Write: BEG-> END.
4. Call TOWER(N-1, AUX, BEG,END)
5.return.
• Moves for 3 disc
• Move disk 1 from A → C
• Move disk 2 from A → B
• Move disk 1 from C → B
• Move disk 3 from A → C
• Move disk 1 from B → A
• Move disk 2 from B → C
• Move disk 1 from A → C
• The time complexity of an algorithm is
• f(n)=2n -1 moves for n disc
• Draw schematic diagram for n =4
Examples(HomeWork)
Suppose S is string with N character. Let SUB(S,J,L) denote
the substring of S beginning in the position J and
length L.
Let A//B denote concatenation of strings A and B.
Suppose REV(S,N) is recursively defined by
REV(S,N) =S if N=1
REV(S,N)=SUB(S,N,1)//REV(SUB(S,1,N-1) otherwise
Find REV(S,N) when
N=3, S=abc
N=5, S=ababc
Cont….
Which best describes what the printString function
below does
public void printString(String s)
{ if (s.length() > 0)
{ printString(s.substring(1));
System.out.print(s.substring(0,1));
} }
A) It prints string s
B) It prints string s in reverse order
C) It prints only the first character of string S
D) it prints only the last character of string S
Cont….
1)Let n denote a positive integer .Suppose function
L is recursively defined as
0 if n=1
L(n)= L(“floor of “(n/2)+1) if n>1
Find L(25) what this function do?
2) Let A be an integer array with N elements.
Suppose X is an integer function defined by
0 if K=0
X(K)=X(A,N,K)= X(K-1)+A(K) if 0<K<=N
X(K-1) if K>N
Find X(5) for N=8 A:3,7,-2,5,6,-4,2,7
Cont….
1) Predict the output of following program. What does the following fun() do in
general?
int fun(int a, int b)
{
if (b == 0)
return 0;
if (b % 2 == 0)
return fun(a+a, b/2);
return fun(a+a, b/2) + a;
}
int main()
{
printf("%d", fun(4, 3));
getchar();
return 0;
}
• Output: 12
• It calulates a*b (a multipied b).