0% found this document useful (0 votes)
99 views

Chapter 6 - Stack and Queue PDF

The document discusses stacks and queues. It begins by defining a stack as a homogeneous collection of elements where an element may only be inserted or deleted from one end, called the top. Common stack operations like push, pop, top, is empty and is full are described. An example is given of using an array to implement a stack and the push and pop algorithms are explained step-by-step with diagrams. Finally, the document briefly discusses order of operations in equations and infix notation.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
99 views

Chapter 6 - Stack and Queue PDF

The document discusses stacks and queues. It begins by defining a stack as a homogeneous collection of elements where an element may only be inserted or deleted from one end, called the top. Common stack operations like push, pop, top, is empty and is full are described. An example is given of using an array to implement a stack and the push and pop algorithms are explained step-by-step with diagrams. Finally, the document briefly discusses order of operations in equations and infix notation.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 92

DATA STRUCTURE

AND
ALGORITHM

Dr. Irfana Memon


Department of CSE, QUEST

https://sites.google.com/a/quest.edu.pk/dr-irfana-memon/lecture-slides
1
NO TOPIC CLO
01 A General Overview CLO1
02 Introduction to Data Structures and Algorithm CLO1
03 String Processing CLO1
04 Abstract Data Types CLO1
05 Linked list CLO2
06 Stack and Queue CLO2
07 Recursion CLO2
08 Complexity Analysis CLO2
09 Sorting and Searching techniques CLO2
10 Trees CLO2
11 Graph CLO3
12 P & NP CLO3

2
CHAPTER 6
Stacks and Queue

3
• What is a Stack?
• DEFINITION:
A stack is a homogeneous collection of
elements in which an element may be inserted or deleted
only at one end, called the top of the stack.

• Formally this type of stack is called a Last In, First Out


(LIFO) stack.

4
• Special terminology is used for two basic operations
associated with stacks:
a) “Push” is the term used to insert an element into a stack.
b) “Pop” is the term used to delete an element from a stack.

5
Suppose the following 6 elements are pushed, in
order, onto an empty stack:
AAA, BBB, CCC, DDD, EEE, FFF
Frequently designate the stack by writing:
STACK : AAA, BBB, CCC, DDD, EEE, FFF

AA BB CCC DD EEE FFF


A B D

1 2 3 4 5 6 7 8 9 10 N-1 N

TOP

6
 To implement a stack, items are inserted and
removed at the same end (called the top)
 To use an array to implement a stack, you need
both the array itself and an integer
 The integer tells you either:
 Which location is currently the top of the stack, or
 How many elements are in the stack

7
STACK

XXX YYY ZZZ

1 2 3 4 5 6 7 8

TOP 3 MAXSTK 8

STACK : A linear array


TOP : A pointer variable, Which contains the location of the top
element of the stack.
MAXSTK : Gives the maximum number of elements that can be
held by the stack.
TOP = 0 or NULL will indicate that the stack is empty
8
 Basic operations that can be performed on a stack:

Push : This operation adds or pushes another item


onto the stack. The number of items on the stack is
less than n.

9
 Basic operations that can be performed on a stack:

Push : This operation adds or pushes another item


onto the stack. The number of items on the stack is
less than n.
Pop: This operation removes an item from the
stack. The number of items on the stack must be
greater than 0.

10
 Basic operations that can be performed on a stack:

Push : This operation adds or pushes another item


onto the stack. The number of items on the stack is
less than n.
Pop: This operation removes an item from the
stack. The number of items on the stack must be
greater than 0.
Top: This operation returns the value of the item at
the top of the stack. Note: It does not remove that
item.

11
 Basic operations that can be performed on a stack:

Push : This operation adds or pushes another item


onto the stack. The number of items on the stack is
less than n.
Pop: This operation removes an item from the
stack. The number of items on the stack must be
greater than 0.
Top: This operation returns the value of the item at
the top of the stack. Note: It does not remove that
item.
Is Empty: This operation returns true if the stack is
empty and false if it is not.

12
 Basic operations that can be performed on a stack:

Push : This operation adds or pushes another item


onto the stack. The number of items on the stack is less
than n.
Pop: This operation removes an item from the stack.
The number of items on the stack must be greater than
0.
Top: This operation returns the value of the item at the
top of the stack. Note: It does not remove that item.
Is Empty: This operation returns true if the stack is
empty and false if it is not.
Is Full: This operation returns true if the stack is full
and false if it is not.

13
Push :
Push is the function used to add data items to the stack.
In order to understand how the Push function operates, we
need to look at the algorithm in more detail.

0 1 2 3 4 5 6 7 8 9
STACK 17 23 97 44

top = 3

MAXSTK= 10 N=4

14
Push :
Push is the function used to add data items to the stack.
In order to understand how the Push function operates, we
need to look at the algorithm in more detail.
0 1 2 3 4 5 6 7 8 9
STACK 17 23 97 44

top = 3 N=4
• ITEM=80 is to be inserted

15
Push :
Push is the function used to add data items to the stack.
In order to understand how the Push function operates, we
need to look at the algorithm in more detail.
0 1 2 3 4 5 6 7 8 9
STACK 17 23 97 44
Item=80
top = 3 N=4
Top=top+1 // top=4
Stack[top]=item
0 1 2 3 4 5 6 7 8 9
• If ITEM=80 is to be inserted
STACK 17 23 97 44 80

top = 4 N=5

16
0 1 2 3 4 5 6 7 8 9
STACK 17 23 97 44

top = 3 N=4
• If ITEM=80 is to be inserted

0 1 2 3 4 5 6 7 8 9

STACK 17 23 97 44 80

top = 4 N=5

Procedure 6.1 : PUSH(STACK, TOP, MAXSTK, ITEM)


1. If TOP = MAXSTK, then : Print :”OVERFLOW”, and
return.
2. Set : TOP := TOP+1.
3. STACK[TOP] := ITEM.
4. Return. 17
Pop :
Data is removed from a stack by using Pop. From a
procedural perspective, pop is called with the line
Pop(item), where item is the variable to store the
popped item in.
Once again, we will begin by looking at the algorithm.
0 1 2 3 4 5 6 7 8 9
STACK 17 23 97 44 80
top = 4 N=5

18
0 1 2 3 4 5 6 7 8 9
STACK 17 23 97 44 80
top = 4 N=5
• If ITEM=80 is to be deleted

0 1 2 3 4 5 6 7 8 9
STACK 17 23 97 44
top = 3 N=4

Procedure 6.2 POP (STACK, TOP, ITEM);


1. If TOP =NULL then : Print :”UNDERFLOW”, and
return.
2. ITEM : =STACK[TOP]) .
3. Set : TOP := TOP-1
4. Return. 19
The binary operation in equation may have different levels of
precedence :

Highest : Exponentiation(↑)
Next highest : Multiplication(*) and division(/)
Lowest : Addition (+) and subtraction (-)
Example :
2 ↑ 3 + 5 *2 ↑ 2 – 12 / 6

20
The binary operation in equation may have different levels of
precedence :

Highest : Exponentiation(↑)
Next highest : Multiplication(*) and division(/)
Lowest : Addition (+) and subtraction (-)
Example :
2 ↑ 3 + 5 *2 ↑ 2 – 12 / 6
Evaluating the Exponentiations :
8 + 5 * 4 -12 / 6

21
The binary operation in equation may have different levels of
precedence :

Highest : Exponentiation(↑)
Next highest : Multiplication(*) and division(/)
Lowest : Addition (+) and subtraction (-)
Example :
2 ↑ 3 + 5 *2 ↑ 2 – 12 / 6
Evaluating the Exponentiations :
8 + 5 * 4 -12 / 6
Evaluating the Multiplication and division
8 + 20 -2

22
The binary operation in equation may have different levels of
precedence :

Highest : Exponentiation(↑)
Next highest : Multiplication(*) and division(/)
Lowest : Addition (+) and subtraction (-)
Example :
2 ↑ 3 + 5 *2 ↑ 2 – 12 / 6
Evaluating the Exponentiations :
8 + 5 * 4 -12 / 6
Evaluating the Multiplication and division
8 + 20 -2
Evaluating the Addition and subtraction
26

23
Infix notation

 Infix notation is the conventional notation for arithmetic


expressions. It is called infix notation because
 each operator is placed between its operands,
 operands (as in the case with binary operators such as addition,
subtraction, multiplication, division,……).
 When parsing expressions written in infix notation, you need
parentheses and precedence rules to remove ambiguity.

 Syntax: operand1 operator operand2


 Example: (A+B)*C -(E+F)

24
 Polish Notation (prefix) :

Polish notation, also known as prefix notation, is a form of


notation for logic, arithmetic, and algebra. Its distinguishing
feature is that it places operators to the left of their operands.
 Lacking parentheses or other brackets.

 Syntax : operator operand1 operand2


 Example : - - *+ABC +EF

 SCANNING Using STACK

25
 Infix expressions into polish (prefix) notation :
(A+B)*C = [+AB]*C = *+ABC

26
 Infix expressions into polish (prefix) notation :
(A+B)*C = [+AB]*C = *+ABC
A+(B*C) = A +[*BC] = +A*BC

27
 Infix expressions into polish (prefix) notation :
(A+B)*C = [+AB]*C = *+ABC
A+(B*C) = A +[*BC] = +A*BC
(A+B)/(C-D) =[+AB]/[-CD] = /+AB-CD

28
 Infix expressions into polish (prefix) notation :
(A+B)*C = [+AB]*C = *+ABC
A+(B*C) = A +[*BC] = +A*BC
(A+B)/(C-D) =[+AB]/[-CD] = /+AB-CD
Fundamental property of polish notation is that the order in
which the operation are to be performed is completely
determined by the positions of the operators and operands in
the expression.

29
Reverse Polish notation (postfix notation)
Reverse Polish notation provided a straightforward solution
for calculator or computer software mathematics because it
treats the instructions (operators) and the data (operands)
as "objects" and processes them in a last-in, first-out (LIFO)
basis.
This is called a "stack method". (Think of a stack of plates.
The last plate you put on the stack will be the first plate
taken off the stack.)

The computer evaluates an arithmetic expression written in


infix notation in two steps.
1. It converts the expression to postfix notation
2. Then it evaluates the postfix expression
In each step stack is main tool that is used to accomplish
the given task
30
 Postfix notation
 In postfix notation, the operator comes after its operands.
Postfix notation is also known as reverse Polish notation
(RPN) and is commonly used because it enables easy
evaluation of expressions.

 Syntax : operand1 operand2 operator


 Example : AB+C*EF+-

SCANNING Using STACK

31
Evaluation of a postfix expression : Let P is an arithmetic
expression written in postfix notation. The following
algorithm, which uses a STACK to hold operands, evaluates P
Algorithm : This algorithm finds the VALUE of an arithmetic
expression P written in postfix notation.

32
AB+
0 1 2 3 4 5 6 7 8 9
STACK 17 23 97 44 80 + A=3 B =12
N=5
top = 4
Evaluation of a postfix expression : Let P is an arithmetic
expression written in postfix notation. The following algorithm,
which uses a STACK to hold operands, evaluates P
Algorithm : This algorithm
x finds the VALUE of an arithmetic
expression P written in postfix notation.
1. Add a right parenthesis “)” at the end of P
2. Scan P from left to right and repeat steps 3 and 4 for each
element of P until the sentinel “)” is encountered.
3. If an operand is encountered, put it on STACK goto step 2.
4. If an operator is encountered, then :
(a) Remove the two top element of STACK, where A
is the top element and B is the next – to – top element.
(b) Evaluate B x A.
(C) Place the result of (b) back on STACK.
[End of if structure]
[End of step 2 loop] 33

Set VALUE equal to the top element on STACK.


Write an algorithm and draw flowchart to find an equivalent
postfix expression for given infix expressions.

34
Quick sort is a divide-and-conquer method for sorting.
Divide and conquer method:
It works by partitioning an array into parts, then sorting each
part independently.

Divide: Partition into sub arrays (sub-


lists), Select a splitting element (pivot)
Rearrange the array (sequence/list)
v

Conquer: Recursively sort 2 sub arrays S


Combine : the sorted S1 (by the time
returned from recursion), followed by v,
followed by the sorted S2 (i.e., nothing
extra needs to be done) v
S1 S2
35
6.5 Quick sort, An
application of stacks
 How do we partition the array efficiently?
 choose partition element to be leftmost element

 scan from left for larger element

 scan from right for smaller element

 exchange

 repeat until pointers cross

36
Example
We are given array of n integers to sort:

40 20 10 80 60 50 7 30 100

37
There are a number of ways to pick the pivot
element. In this example, we will use the first
element in the array:

40 20 10 80 60 50 7 30 100
[0] [1] [2] [3] [4] [5] [6] [7] [8]

LOC=0 ; LEFT = 0 and RIGHT = 8

38
LOC = 0 40 20 10 80 60 50 7 30 100

[0] [1] [2] [3] [4] [5] [6] [7] [8]

LEFT = 0 RIGHT = 8
LOC=0 ; LEFT = 0 and RIGHT = 8
SCAN From right to left, IF INFO[RIGHT] < INFO[LEFT]
THEN INTERCHANGE
i.e., 100 < 40 (No interchange)
RIGHT:= RIGHT-1

39
LOC = 0 40 20 10 80 60 50 7 30 100

[0] [1] [2] [3] [4] [5] [6] [7] [8]

LEFT = 0 RIGHT = 8
LOC=0 ; LEFT = 0 and RIGHT = 8
SCAN From right to left, IF INFO[RIGHT] < INFO[LEFT]
THEN INTERCHANGE
i.e., 100 < 40 (No interchange)
RIGHT:= RIGH-1

LOC = 0 40 20 10 80 60 50 7 30 100

[0] [1] [2] [3] [4] [5] [6] [7] [8]

LEFT = 0 RIGHT = 7
40
LOC = 0 40 20 10 80 60 50 7 30 100

[0] [1] [2] [3] [4] [5] [6] [7] [8]

LEFT = 0 RIGHT = 7
LOC=0 ; LEFT = 0 and RIGHT = 7

SCAN From right to left, IF INFO[RIGHT] < INFO[LEFT] THEN


INTERCHANGE
i.e., 30 < 40 (Interchange)
LEFT = LEFT+1
=
LOC = 7 30 20 10 80 60 50 7 40 100

[0] [1] [2] [3] [4] [5] [6] [7] [8]

LEFT = 1 RIGHT = 7
41
LOC = 7 30 20 10 80 60 50 7 40 100
[0] [1] [2] [3] [4] [5] [6] [7] [8]

LEFT = 1 RIGHT = 7

LOC=7 ; LEFT = 1 and RIGHT = 7

SCAN From Left to Right, IF INFO[LEFT] > INFO[RIGHT] THEN


INTERCHANGE
i.e., 20 > 40 (No Interchange)
LEFT = LEFT+1

42
LOC = 7 30 20 10 80 60 50 7 40 100
[0] [1] [2] [3] [4] [5] [6] [7] [8]

LEFT = 1 RIGHT = 7

LOC=7 ; LEFT = 1 and RIGHT = 7

SCAN From Left to Right, IF INFO[LEFT] > INFO[RIGHT] THEN


INTERCHANGE
i.e., 20 > 40 (No Interchange)
LEFT = LEFT+1

LOC = 7 30 20 10 80 60 50 7 40 100

[0] [1] [2] [3] [4] [5] [6] [7] [8]

LEFT = 2 RIGHT = 7
43
LOC = 7 30 20 10 80 60 50 7 40 100

[0] [1] [2] [3] [4] [5] [6] [7] [8]

LEFT = 2 RIGHT = 7

LOC=7 ; LEFT = 1 and RIGHT = 7

SCAN From Left to Right, IF INFO[LEFT] > INFO[RIGHT] THEN


INTERCHANGE
i.e., 10 > 40 (No Interchange)
LEFT = LEFT+1

LOC = 7 30 20 10 80 60 50 7 40 100
[0] [1] [2] [3] [4] [5] [6] [7] [8]

LEFT = 3 RIGHT
44 =7
LOC = 7 30 20 10 80 60 50 7 40 100

[0] [1] [2] [3] [4] [5] [6] [7] [8]

LEFT = 3 RIGHT = 7

LOC=7 ; LEFT = 3 and RIGHT = 7

SCAN From Left to Right, IF INFO[LEFT] > INFO[RIGHT] THEN


INTERCHANGE
i.e., 80 > 40 (Interchange)
RIGHT = RIGHT-1

LOC = 3 30 20 10 40 60 50 7 80 100
[0] [1] [2] [3] [4] [5] [6] [7] [8]

LEFT = 3 RIGHT = 6
45
LOC = 3 30 20 10 40 60 50 7 80 100
[0] [1] [2] [3] [4] [5] [6] [7] [8]

LEFT = 3 RIGHT = 6

LOC=3 ; LEFT = 3 and RIGHT = 6

SCAN From right to left, IF INFO[RIGHT] < INFO[LEFT] THEN


INTERCHANGE
i.e., 7 < 40 (Interchange)
LEFT = LEFT+1

LOC = 6 30 20 10 7 60 50 40 80 100
[0] [1] [2] [3] [4] [5] [6] [7] [8]

LEFT = 4 RIGHT = 6
46
LOC = 6 30 20 10 7 60 50 40 80 100
[0] [1] [2] [3] [4] [5] [6] [7] [8]

LEFT = 4 RIGHT = 6
LOC=3 ; LEFT = 3 and RIGHT = 6

SCAN From left to right, IF INFO[LEFT] > INFO[RIGHT] THEN


INTERCHANGE
i.e., 60 > 40 (Interchange)
RIGHT = RIGHT-1

LOC = 4 30 20 10 7 40 50 60 80 100
[0] [1] [2] [3] [4] [5] [6] [7] [8]

LEFT = 4 RIGHT = 5
47
LOC = 4 30 20 10 7 40 50 60 80 100

[0] [1] [2] [3] [4] [5] [6] [7] [8]

LEFT = 4 RIGHT = 5

30 20 10 7 40 50 60 80 100
[0] [1] [2] [3] [4] [5] [6] [7] [8]

First sublist second sublist

Apply the above procedure repetitively until each sub list contains
one element

48
1. Set LEFT = BEG, RIGHT = END and LOC = LEFT

LOC = 0 40 20 10 80 60 50 7 30 100
[0] [1] [2] [3] [4] [5] [6] [7] [8]

LEFT = 0 RIGHT = 8
49
1. Set LEFT = BEG, RIGHT = END and LOC = LEFT
2. (a) Repeat A[LOC] <= A[RIGHT] and LOC ≠ RIGHT
RIGHT := RIGHT -1
(b) if LOC =RIGHT then return
(c) If A[LOC] > A[RIGHT]
(i) interchange each other
(ii) LOC =RIGHT
(iii) Goto Step 3

LOC = 0 40 20 10 80 60 50 7 30 100

[0] [1] [2] [3] [4] [5] [6] [7] [8]

LEFT = 0 RIGHT = 8

50
1. Set
1. SetLEFT = BEG,
LEFT RIGHTRIGHT
= BEG, = END and LOC =and
= END LEFTLOC = LEFT

2. (a) Repeat A[LOC] <= A[RIGHT] and LOC ≠ RIGHT


RIGHT := RIGHT -1
(b) if LOC =RIGHT then return
(c) If A[LOC] > A[RIGHT]
(i) interchange each other
(ii) LOC =RIGHT
(iii) Goto Step 3

LOC = 0 40 20 10 80 60 50 7 30 100
[0] [1] [2] [3] [4] [5] [6] [7] [8]

LEFT = 0 RIGHT = 7
51
1. Set
1. SetLEFT = BEG,
LEFT RIGHTRIGHT
= BEG, = END and LOC =and
= END LEFTLOC = LEFT

2. (a) Repeat A[LOC] <= A[RIGHT] and LOC ≠ RIGHT


RIGHT := RIGHT -1
(b) if LOC =RIGHT then return
(c) If A[LOC] > A[RIGHT]
(i) interchange each other
(ii) LOC =RIGHT
(iii) Goto Step 3
3. (a) Repeat A[LOC] > A[LEFT] and LOC ≠ LEFT
LEFT := LEFT +1
(b) if LOC = LEFT then return
(c) If A[LEFT] > A[LOC]
(i) interchange each other
(ii) LOC =LEFT
(iii) Goto Step 2

LOC = 7 30 20 10 80 60 50 7 40 100
[0] [1] [2] [3] [4] [5] [6] [7] [8]

LEFT = 0 RIGHT = 7
52
1. Set
1. SetLEFT = BEG,
LEFT RIGHTRIGHT
= BEG, = END and LOC =and
= END LEFTLOC = LEFT

2. (a) Repeat A[LOC] <= A[RIGHT] and LOC ≠ RIGHT


RIGHT := RIGHT -1
(b) if LOC =RIGHT then return
(c) If A[LOC] > A[RIGHT]
(i) interchange each other
(ii) LOC =RIGHT
(iii) Goto Step 3
3. (a) Repeat A[LOC] > A[LEFT] and LOC ≠ LEFT
LEFT := LEFT +1
(b) if LOC = LEFT then return
(c) If A[LEFT] > A[LOC]
(i) interchange each other
(ii) LOC =LEFT
(iii) Goto Step 2

LOC = 7 30 20 10 80 60 50 7 40 100
[0] [1] [2] [3] [4] [5] [6] [7] [8]

LEFT = 1 RIGHT = 7
53
1. Set
1. SetLEFT = BEG,
LEFT RIGHTRIGHT
= BEG, = END and LOC =and
= END LEFTLOC = LEFT

2. (a) Repeat A[LOC] <= A[RIGHT] and LOC ≠ RIGHT


RIGHT := RIGHT -1
(b) if LOC =RIGHT then return
(c) If A[LOC] > A[RIGHT]
(i) interchange each other
(ii) LOC =RIGHT
(iii) Goto Step 3
3. (a) Repeat A[LOC] > A[LEFT] and LOC ≠ LEFT
LEFT := LEFT +1
(b) if LOC = LEFT then return
(c) If A[LEFT] > A[LOC]
(i) interchange each other
(ii) LOC =LEFT
(iii) Goto Step 2

LOC = 7 30 20 10 80 60 50 7 40 100
[0] [1] [2] [3] [4] [5] [6] [7] [8]

LEFT = 2 RIGHT = 7
54
1. Set
1. SetLEFT = BEG,
LEFT RIGHTRIGHT
= BEG, = END and LOC =and
= END LEFTLOC = LEFT

2. (a) Repeat A[LOC] <= A[RIGHT] and LOC ≠ RIGHT


RIGHT := RIGHT -1
(b) if LOC =RIGHT then return
(c) If A[LOC] > A[RIGHT]
(i) interchange each other
(ii) LOC =RIGHT
(iii) Goto Step 3
3. (a) Repeat A[LOC] > A[LEFT] and LOC ≠ LEFT
LEFT := LEFT +1
(b) if LOC = LEFT then return
(c) If A[LEFT] > A[LOC]
(i) interchange each other
(ii) LOC =LEFT
(iii) Goto Step 2

LOC = 7 30 20 10 80 60 50 7 40 100
[0] [1] [2] [3] [4] [5] [6] [7] [8]

LEFT = 3 RIGHT = 7
55
This algorithm sorts an array A with N elements

1. [Initialize] TOP=NULL.
2. [Push boundary values of A onto stack when A has 2 or more elements]
If N>1, then TOP:=TOP+1, LOWER[1]:=1 and UPPER[1]:=N.
3. Repeat Step 4 to 7 while TOP!= NULL.
4. [Pop sub list from stack]
Set BEG:=LOWER[TOP], END:=UPPER[TOP]
TOP:=TOP-1.
5. Call QUICK(A,N,BEG,END,LOC). [Procedure 6.5]
6. [Push left sub list 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 sub list onto stacks when it has 2 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
56
 A function is said to be recursively defined, if a
function containing either a Call statement to itself
or a Call statement to a second function that may
eventually result in a Call statement back to the
original function.
 A recursive function must have the following
properties:
1. There must be certain criteria, called base
criteria for which the function does not call itself.
2. Each time the function does call itself
(directly or indirectly), the argument of the function
must be closer to a base value

57
 Factorial function: In general, we can express the
factorial function as follows: n! = n * (n-1)!
 The factorial function is only defined for positive
integers.
 if n<=1, then n! = 1
 if n>1, then n! = n * (n-1)!

58
Procedure : FACTORIAL(FACT, N)
This procedure calculates N! and return the value in the variable FACT.

59
Step 1. start
Step 2 .Input the value of N
Step 3. FACTORIAL(FACT,N)
Step 4. Write FACT
Step 5. Exit

Procedure : FACTORIAL(FACT, N)
This procedure calculates N! and return the value in the variable FACT.
1. If N=0, then: Set FACT :=1, and Return
2. Set FACT = 1.
3. Repeat for K=1 to N
Set FACT : = K*FACT
4. Return.

60
Fibonacci Sequence : 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55,…………………

61
Fibonacci Sequence : 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55,…………………
Definition 6.2
(a) If n=0 or n=1, then Fn =n
(b) If n>1, then Fn =Fn-2 +Fn-1.

62
Fibonacci Sequence : 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55,…………………
Definition 6.2
(a) If n=0 or n=1, then Fn =n
(b) If n>1, then Fn =Fn-2 +Fn-1.

Procedure: FIBONACCI(FIB, N)
This procedure calculates Fn and returns the value in the first
parameter FIB.

63
Fibonacci Sequence : 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55,…………………
Definition 6.2
(a) If n=0 or n=1, then Fn =n
(b) If n>1, then Fn =Fn-2 +Fn-1.

Procedure: FIBONACCI(FIB, N)
This procedure calculates Fn and returns the value in the first
parameter FIB.
1. If N=0 or N=1, then : set FIB :=N, and return.

2. Call FIBONACCI(FIBA, N-2).

3. Call FIBONACCI(FIBB, N-1).

4. Set FIB : =FIBA +FIBB.

5. Return. 64
65
 Disks of different sizes (call the number of disks "n") are placed on
the left hand post,
 arranged by size with the smallest on top.
 You are to transfer all the disks to the right hand post in the fewest
possible moves, without ever placing a larger disk on a smaller one.

The object is to move all the disks over to another pole. But
you cannot place a larger disk onto a smaller disk.

66
 How many moves will it take to transfer n disks from the
left post to the right post?
 Let's look for a pattern in the number of steps it takes to move
just one, two, or three disks. We'll number the disks starting
with disk 1 on the bottom.1 disk: 1 move
 Move 1: move disk 1 to post C

67
2 disks: 3 moves
Move 1: move disk 2 to post B
Move 2: move disk 1 to post C
Move 3: move disk 2 to post C

68
3 disks: 7 moves
Move 1: move disk 3 to post C
Move 2: move disk 2 to post B
Move 3: move disk 3 to post B
Move 4: move disk 1 to post C
Move 5: move disk 3 to post A
Move 6: move disk 2 to post C
Move 7: move disk 3 to post C

69
3 disks: 3 moves
 Its solution touches on two important topics :

 A. recursive functions and stacks


 B. recurrence relations

 B. Recurrence relations
 Let TN be the minimum number of moves needed to solve the puzzle
with N disks. From the previous section T1 = 1, T2 = 3 and T3 = 7
 A trained mathematician would also note that T0 = 0. Now let us try
to derive a general formula.

 Thus we can define the quantity TN as


 T0 = 0
TN = 2TN-1 + 1 for N > 0 We may compute
 T1 = 2T0 + 1 = 1,
 T2 = 2T1 + 1= 3,
 T3 = 2T2 + 1 = 7
 T4 = 2T3 + 1 = 15 and so on sequentially.

70
 A. Recursive pattern
 From the moves necessary to transfer one, two, and three disks, we can
find a recursive pattern - a pattern that uses information from one step
to find the next step - for moving n disks from post A to post C:
 First, transfer n-1 disks from post A to post B. The number of moves
will be the same as those needed to transfer n-1 disks from post A to
post C. Call this number M moves. [As you can see above, with three
disks it takes 3 moves to transfer two disks (n-1) from post A to post C.]
 Next, transfer disk 1 to post C [1 move].
 Finally, transfer the remaining n-1 disks from post B to post C. [Again,
the number of moves will be the same as those needed to transfer n-1
disks from post A to post C, or M moves.]

for 1 disk it takes 1 move to transfer 1 disk from post A to post C;


for 2 disks, it will take 3 moves: 2M + 1 = 2(1) + 1 = 3
for 3 disks, it will take 7 moves: 2M + 1 = 2(3) + 1 = 7
for 4 disks, it will take 15 moves: 2M + 1 = 2(7) + 1 = 15
for 5 disks, it will take 31 moves: 2M + 1 = 2(15) + 1 = 31
for 6 disks... ?
71
TOWER(N, BEG, AUX, END)
Write procedure gives a recursive solution to the
Towers of Hanoi problem for N disks.

72
 A Queue is a linear list of elements in which deletions can take
place only at one end, called the front, and insertions can take
place only at the other end, called the rear. The terms “front”
and “rear” are used in describing a linear list only when it
implemented as a queue.
 Queues are also called first-in first-out (FIFO) lists, since the
first element in a queue will be the first element out of the
queue. In other words, the order in which elements enter a
queue is the order in which they leave. This contrasts with
stacks, which are Last-in First-out (LIFO) lists.

73
 The people waiting in line at a bank form a queue, where the
first person in line is the first person to be waited on; and so on.
 An important example of a queue in computer science occurs in a
timesharing system, in which programs with the same priority
form a queue while waiting to be executed.
 Queue for printing purposes

74
 Create queue, Create (Q)
 Identify either queue is empty
 Add new item in queue
 Delete item from queue
 Call first item in queue

75
 Queue may be represented in the computer in various ways,
usually by means of one-way lists or linear arrays.
 Each of our queues will be maintained by a linear array
QUEUE and two pointer variables:
 FRONT, containing the location of the front element of the
queue;
 and REAR, containing the location of the rear element of the
queue.
 The condition FRONT = NULL will indicate that the queue is
empty.

76
 when an element is deleted from the queue, the value of FRONT is
increased by 1; this can be implemented by the assignment
 FRONT := FRONT + 1
 Similarly, whenever an element is added to the queue, the value of
REAR is increased by 1; this can be implemented by the assignment
 REAR := REAR + 1
 This means that after N insertions, the rear element of the queue will
occupy QUEUE[N] or, in other words, eventually the queue will occupy
the last part of the array. This occurs even through the queue itself may
not contain many elements.

77
QINSERT(QUEUE,N,FRONT,REAR,ITEM)
This procedure inserts an element ITEM into a queue.

78
QINSERT(QUEUE,N,FRONT,REAR,ITEM)
This procedure inserts an element ITEM into a queue.

[Queue already fill]


1. If FRONT=1 and REAR=N, then :
Write: Overflow, and Return.

79
QINSERT(QUEUE,N,FRONT,REAR,ITEM)
This procedure inserts an element ITEM into a queue.

[Queue already fill]


1. If FRONT=1 and REAR=N, then :
Write: Overflow, and Return.
2. [Find new value of REAR]
If FRONT=NULL, then :[Queue initially empty]
Set FRONT:=1 and REAR:=1
Else
Set REAR:=REAR+1
[End of if structure]

80
QINSERT(QUEUE,N,FRONT,REAR,ITEM)
This procedure inserts an element ITEM into a queue.

[Queue already fill]


1. If FRONT=1 and REAR=N, then :
Write: Overflow, and Return.
2. [Find new value of REAR]
If FRONT=NULL, then :[Queue initially empty]
Set FRONT:=1 and REAR:=1
Else
Set REAR:=REAR+1
[End of if structure]
3. Set QUEUE[REAR]:=ITEM [This inserts new element]
4. Return

81
ITEM.QDELETE(QUEUE,N,FRONT,REAR,ITEM)
This procedure deletes an element from the queue and assigns it
to the variable

82
ITEM.QDELETE(QUEUE,N,FRONT,REAR,ITEM)
This procedure deletes an element from the queue and assigns it to
the variable
1. [Queue already empty]
If FRONT = NULL, then Write: Underflow, and Return.

83
ITEM.QDELETE(QUEUE,N,FRONT,REAR,ITEM)
This procedure deletes an element from the queue and assigns it to
the variable
1. [Queue already empty]
If FRONT = NULL, then Write: Underflow, and Return.
2. Set ITEM = QUEUE[FRONT]

84
ITEM.QDELETE(QUEUE,N,FRONT,REAR,ITEM)
This procedure deletes an element from the queue and assigns it to
the variable
1. [Queue already empty]
If FRONT = NULL, then Write: Underflow, and Return.
2. Set ITEM = QUEUE[FRONT]
3. [Find new value of FRONT]
If FRONT=REAR, then [Queue has only one element to start]
Set FRONT=NULL and REAR=NULL

85
ITEM.QDELETE(QUEUE,N,FRONT,REAR,ITEM)
This procedure deletes an element from the queue and assigns it to
the variable
1. [Queue already empty]
If FRONT = NULL, then Write: Underflow, and Return.
2. Set ITEM = QUEUE[FRONT]
3. [Find new value of FRONT]
If FRONT=REAR, then [Queue has only one element to start]
Set FRONT=NULL and REAR=NULL
Else if FRONT =N then
Set FRONT =1

86
ITEM.QDELETE(QUEUE,N,FRONT,REAR,ITEM)
This procedure deletes an element from the queue and assigns it to
the variable
1. [Queue already empty]
If FRONT = NULL, then Write: Underflow, and Return.
2. Set ITEM = QUEUE[FRONT]
3. [Find new value of FRONT]
If FRONT=REAR, then [Queue has only one element to start]
Set FRONT=NULL and REAR=NULL
Else if FRONT =N then
Set FRONT =1
Else
Set FRONT = FRONT +1
[End of if structure]
4. Return
87
 The mathematical model of a Deque (usually pronounced like
"deck") is an irregular acronym (Operation) of double-ended
queue.
 Double-ended queues are a kind of sequence containers.
 Elements can be efficiently added and removed from any of its
ends (either the beginning or the end of the sequence).

• The model allows data to be entered and withdrawn from the


front
and rear of the data structure.

88
 Insertions and deletions can occur at either end but not in the
middle
 Implementation is similar to that for queues
 Deques are not heavily used
 You should know what a deque is, but we won’t explore them
much further

89
• There are two variations of deque
–Input-restricted deque
An input restricted deque is a deque which allows insertion
at only one end of the list but allows deletion a both end of
the list.
–Output-restricted deque
An output restricted deque is a deque which allows
deletion at only one end of the list but allows insertin a
both end of the list

90
 A priority queue is a collection of elements such that each
element has been assigned a priority, such that the order in
which the elements are deleted and processed comes from
the following rules:

 An element with higher priority will be processed before


any element with lower priority.
 Two elements with the same priority will be processed in
order in which they are add to the queue.

91
Wish
You
Good Luck

92

You might also like