40
Stacks, Queues & Recursion Stacks: LIFO Last In First Out Queues: FIFO First In First Out

Stacks, Queues & Recursion

  • Upload
    phyre

  • View
    61

  • Download
    0

Embed Size (px)

DESCRIPTION

Stacks, Queues & Recursion. Stacks:LIFO Last In First Out Queues: FIFO First In First Out. QUEUESFIFO. AAA Front DDD Rear. DDD. AAA. BBB. CCC. - PowerPoint PPT Presentation

Citation preview

Page 1: Stacks, Queues & Recursion

Stacks, Queues & Recursion

Stacks: LIFO Last In First Out

Queues: FIFO First In First Out

Page 2: Stacks, Queues & Recursion

QUEUES FIFO• Queue is a linear structure in which Deletions

can take place at one end only, called the Front and Insertions can take place only at other end, called the Rear.

• Three everyday examples of such a structure– Waiting Automobiles for Fuel– People Waiting in Line at Bank– Programs with the same Priority– Another structure called priority queue

AAA BBB CCC DDD AAA Front DDD Rear

Page 3: Stacks, Queues & Recursion

Representation of Queues

• FRONT: Containing the Location of the Front Element

• REAR: Containing the Location of the Rear Element

• FRONT = NULL will indicate the Queue is Empty• Deletion: FRONT := FRONT + 1 • Insertion: REAR := REAR + 1• After N Insertions, the Rear Element of the

Queue will Occupy QUEUE [N]

Page 4: Stacks, Queues & Recursion

Representation of Queues Cont…

FRONT-1 AAA BBB CCC DDD ……. ……. ……

REAR -4 1 2 3 4 5 6 N

FRONT-2 BBB CCC DDD ……. ……. ……

REAR -4 1 2 3 4 5 6 N

FRONT-2 BBB CCC DDD EEE FFF ……

REAR -6 1 2 3 4 5 6 N

FRONT-3 CCC DDD EEE FFF ……

REAR -6 1 2 3 4 5 6 N

Page 5: Stacks, Queues & Recursion

Circular Queues• QUEUE [1] comes after QUEUE [N] in the array• Instead of increasing REAR to N+1 we reset REAR=1

– QUEUE [REAR]:= ITEM • Instead of Increasing FRONT to N+1 we reset

FRONT= 1• Queue contains only one Element

– FRONT = REAR NULL• For No Element

– FRONT := NULL– REAR := NULL

Page 6: Stacks, Queues & Recursion

(a) Initially Empty FRONT-0

REAR -0 1 2 3 4 5

(b) A,B,C FRONT-1 A B C

Inserted REAR -3 1 2 3 4 5

(c) A Deleted FRONT-2 B C

REAR - 3 1 2 3 4 5

(d) D and then FRONT-2 B C D E

E Inserted REAR - 5 1 2 3 4 5

(e) B and C FRONT-4 D E

Deleted REAR - 5 1 2 3 4 5

Page 7: Stacks, Queues & Recursion

(f) F Inserted FRONT-4 F D E

REAR -1 1 2 3 4 5

(g) D Deleted FRONT-5 F E

REAR -1 1 2 3 4 5

(h) G and then FRONT-5 F G H E

H Inserted REAR -3 1 2 3 4 5

(i) E Deleted FRONT-1 F G H

REAR -3 1 2 3 4 5

(j) F Deleted FRONT-2 G H

REAR -3 1 2 3 4 5

Page 8: Stacks, Queues & Recursion

(k) K Inserted FRONT-2 G H K

REAR -4 1 2 3 4 5

(l) G and H FRONT-4 K

Deleted REAR -4 1 2 3 4 5

(m) K Deleted FRONT-0

Queue Empty REAR -0 1 2 3 4 5

Page 9: Stacks, Queues & Recursion

This procedure inserts an element ITEM into a queue.1. [Queue already filled?]

If FRONT =1 and REAR = N, or if FRONT=REAR+1Then write: OVERFLOW and return

2. [Find new value of REAR]If FRONT:=NULL [QUEUE Initially empty]Then : Set FRONT:=1 and REAR:=1Else If REAR =N then Set REAR:=1Else:Set REAR:=REAR+1[End of If structure]

3. Set QUEUE[REAR]:=ITEM [ This inserts new element]4. Return

QINSERT (QUEUE, N, FRONT, REAR, ITEM)

Page 10: Stacks, Queues & Recursion

QDELETE (QUEUE, N, FRONT, REAR, ITEM)

This procedure deletes an element from a queue andassigns it to the variable item.1. [QUEUE already empty?]

If FRONT:=NULL, then write: UNDERFLOW and Return2. 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:=NULLElse if FRONT:=N then Set FRONT:=1ElseSet FRONT:=FRONT+1[End of If Structure]

4. Return

Page 11: Stacks, Queues & Recursion

STACKS LIFO

• A stack is a linear structure in which items are added or removed only at one end.

• Three everyday examples of such a structure– Stack of dishes– Stack of pennies– Stack of folded towels

• In particular the last item to be added to stack is the first item to be removed

• STACKS are also called “PILES” AND “PUSH- DOWN”

Page 12: Stacks, Queues & Recursion

Operations On Stack• PUSH: is the term to insert an element into a stack• POP: is the term to delete an element from a stack• Example: Suppose the following 6 elements are

pushed in order onto an empty stack• AAA, BBB, CCC, DDD, EEE, FFF• This means:

– EEE cannot be deleted before

FFF is deleted,– DDD cannot be deleted before

EEE and FFF is deleted and so on.

AAA

BBB

CCC

DDD

EEE

FFF

AAA

BBB

CCC

DDD

EEE

FFF

TOP

Page 13: Stacks, Queues & Recursion

POSTPONED DECISIONS

• Stacks are frequently used to indicate the order of the processing of data when certain steps of the processing must be postponed until other conditions are fulfilled.

B

AB

A ABC

Page 14: Stacks, Queues & Recursion

Operation Of Stack• CreateStack (Size)

– Function: Initialize Stack to an Empty State– Input: None– Precondition: None– Output: Stack– Post condition: Stack is Empty

• DestroyStack(Stack)– Function: Remove all the Elements from Stack– Input: Stack– Precondition: Stack has been created– Output: Stack

– Post condition: Stack is Empty

Page 15: Stacks, Queues & Recursion

Operation Of Stack Cont….• EmptyStack (Stack)

– Function: Test whether stack is Empty– Input: Stack– Precondition: Stack has been created– Output: EmptyStack (Boolean)

• FullStack(Stack)– Function: Test whether stack is Full– Input: Stack– Precondition: Stack has been created

– Output: FullStack (Boolean)

Page 16: Stacks, Queues & Recursion

Operation Of Stack Cont….• Push (Stack, NewValue)

– Function: Add new value in a Stack– Input: Stack, New Value– Precondition: Stack has been created and not Full– Output: Stack– Post condition: New Value will be added in the Stack

New Top will be assigned

• Pop(Stack, PoppedValue)– Function: Remove the top value from the Stack– Input: Stack– Precondition: Stack has been created and not Empty– Output: Stack, Popped Value

– Post condition: New Top will be assigned

Page 17: Stacks, Queues & Recursion

• PUSH (STACK, TOP, MAXSTR, ITEM)– This procedure pushes an ITEM onto a stack

1. If TOP = MAXSTR, then Print: OVERFLOW, and Return.

2.Set TOP := TOP + 1 [Increases TOP by 1]

3.Set STACK [TOP] := ITEM. [Insert ITEM in TOP position]

4.Return

• POP (STACK, TOP, ITEM)– This procedure deletes the top element of STACK and

assign it to the variable ITEM

1.If TOP = 0, then Print: UNDERFLOW, and Return.

2.Set ITEM := STACK[TOP]

3.Set TOP := TOP - 1 [Decreases TOP by 1]

4.Return

Page 18: Stacks, Queues & Recursion

Arithmetic Expressions• Precedence Level

– Highest Exponentiation ( ) – Next Highest Multiplication (*) and Division ( / )– Lowest: Addition (+) and subtraction (-)

• Infix Notation– A + B C – D (G / H) + A

• Polish Notation (Prefix Notation)– + AB - CD (/ GH) + A = + / GHA

• Reverse Polish Notation (Postfix or Suffix Notation) – AB + CD - GHA / +

Page 19: Stacks, Queues & Recursion

Evaluation of Expression• The Computer Usually Evaluates an Arithmetic expression

written in infix notation into steps

1. First converts the expression to postfix notation

2. Evaluates the postfix expression

• Stack is the Main Tool that is Used to Accomplish given Task.

INFIX PREFIX

( A + B ) * C [ + A B ] * C = * + A B

A + ( B * C ) A + [ * B C ] = + A * B C

( A + B ) / ( C – D ) [+ AB] / [- CD] = / + AB-CD

Page 20: Stacks, Queues & Recursion

• This Algorithm 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 step 3 and 4 for each element of P until “)”is encountered.

3. If an operand is encountered, put it in STACK.

4. If an operator X is encountered then:

a) Remove the two top elements of STACK

b) Evaluate B X A

c) Place the result of (b) back on STACK.

5. [End of IF Structure]

6. [End of STEP2 loop]

7. Set VALUE equal to the top element on STACK.

8. Exit

Page 21: Stacks, Queues & Recursion

Stack Postfix Operation• Q: 5 * ( 6 + 2 ) – 12 / 4• P : 5 , 6 , 2 , + , * , 12 , 4 , / , - , )

Symbol Scanned STACK

1. 5 5

2. 6 5,6

3. 2 5,6,2

4. + 5,8

5. * 40

6. 12 40,12

7. 4 40, 12, 4

8. / 40, 3

9. - 37

10. )

Page 22: Stacks, Queues & Recursion

Transforming Infix to Postfix• The following Algorithm Transforms the Infix Expression Q into its

Equivalent Postfix Expression P• The Algorithm uses a STACK to Temporarily Hold Operators and

Left Parentheses.• The Postfix Expression P will be Constructed from Left to Right

using the Operands and Left Parentheses. • The Postfix Expression P will be Constructed from Left to Right

using the Operands from Q and the Operators which are Removed from STACK

• We begin by Pushing a Left Parenthesis onto STACK and Adding Right Parentheses at the End of Q

• The Algorithm is Completed when STACK is Empty.

Page 23: Stacks, Queues & Recursion

Algorithm: POLISH (Q, P)1. PUSH “(” onto STACK, and add “)” to the end of Q 2. Scan Q from left to right and repeat step 3 to step 6 for each element of Q until

the STACK is empty.3. If an operands is encountered, add it to P4. If a left parenthesis is encountered, push it onto STACK5. If an operator X is encountered then:

a) Repeatedly POP from STACK and add to P each operator (on the top of STACK) which has the same precedence as or higher precedence than X

b) Add X to STACK[END of IF Structure]

6. If a right parenthesis is encountered then:a) Repeatedly POP from STACK and add to P each operator (on the top of

STACK) until a left parenthesis is encountered.b) Remove the left parenthesis

[END of IF Structure][END of STEP 2 loop]

7. EXIT

Page 24: Stacks, Queues & Recursion

Q: A + ( B * C - ( D / E F ) * G ) * H ) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

Symbol STACK Expression P

(1) A ( A

(2) + ( + A

(3) ( ( + ( A

(4) B ( + ( A B

(5) * ( + ( * A B

(6) C ( + ( * A B C

(7) - ( + ( - A B C *

(8) ( ( + ( - ( A B C *

(9) D ( + ( - ( A B C * D

(10) / ( + ( - ( / A B C * D

(11) E ( + ( - ( / A B C * D E

Page 25: Stacks, Queues & Recursion

Q: A + ( B * C - ( D / E F ) * G ) * H ) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

Symbol STACK Expression P(12) ( + ( - ( / A B C * D E(13) F ( + ( - ( / A B C * D E F(14) ) ( + ( - A B C * D E F /(15) * ( + ( - * A B C * D E F /(16) G ( + ( - * A B C * D E F / G(17) ) ( + A B C * D E F / G * -(18) * ( + * A B C * D E F / G * -(19) H ( + * A B C * D E F / G * - H(20) ) A B C * D E F / G * - H * +

P: A B C * D E F / G * - H * +

Page 26: Stacks, Queues & Recursion

RECURSION Recursive Procedure and Function

• Recursion occurs when a Procedure call itself

• A Procedure call some other procedure that calls the calling Procedure again

• It is called a Recursive Procedure

• Procedure must contain a base criteria

• Procedure must be closer to the base criteria after each call

• It is called a Well Defined procedure

Page 27: Stacks, Queues & Recursion

Factorial Function

• Product of Positive Integer from 1 to n

• Denoted by n! => n! = 1.2.3….(n-2).(n-1).n

• 0! = 1 , 5! = 1.2.3.4.5 = 120, 6! = 5! . 6 = 720

• n! = n . ( n – 1 )!

• Definition– If n = 0 then n! = 1– If n > 0, then n! = n. (n-1) !

Page 28: Stacks, Queues & Recursion

• Example: Postpone Decision

1 4! = 4 . 3!2 3! = 3 . 2!3 2! = 2. 1!4 1! = 1. 0!5 0! = 16 1! = 1.1 = 17 2! = 2.1 = 28 3! = 3.2 = 69 4! = 4.6 = 24

Page 29: Stacks, Queues & Recursion

• FACTORIAL (FACT,N)1 If N = 0 then Set FACT = 1 and Return

2 Set FACT := 1 [Initialize FACT for loop]

3 Repeat for K = 1 to N

Set FACT := K * FACT

[End of Loop]

4 Return

• FACTORIAL (FACT, N)1 If N = 0 then Set FACT = 1 and Return

2 Call FACTORIAL (FACT, N – 1)

3 Set FACT := N * FACT

4 Return

• Reading Assignments: Level Number and Depth of Recursion

Page 30: Stacks, Queues & Recursion

DEQUES

• Input Restricted Deque– Insertion at Only One End but Deletion

from Both Ends

• Output Restricted Deque– Deletion from One End but Insertion at

Both Ends

Page 31: Stacks, Queues & Recursion

PRIORITY QUEUES

• Each Element has its own priority – Higher Priority Elements will Processed

before Lower Priority Elements– Same Priority Elements will Processed

According to their Order

• Can be Implemented by a One-Way List or Multiple Queues

• Reading Assignment Array Representation of Priority Queues

Page 32: Stacks, Queues & Recursion

One-Way List Implementation

• Each Node Contain Three Fields– INFO Field: Contains the Data– PRN Field : Contains the Priority Number– LINK Field : Link to the Next Node

1 2 2

3 4 5

Start

AAA BBB CCC

DDD EEE FFF

3GGG

Page 33: Stacks, Queues & Recursion

Quick Sort An Stacks Application• Quick Sort works on Divide and Conquer Rule• Quick Sort Strategy is to Divide a List or Set into

Two Sub-Lists or Sub-Sets. • Pick an Element, Called a Pivot, from the List. • Reorder the List so that all Elements which are

Less than the Pivot come Before the Pivot and so that All Elements Greater than the Pivot come After it. After this Partitioning, the Pivot is in its Final Position. This is called the Partition operation.

• Recursively Sort the Sub-List of Lesser Elements and the Sub-List of Greater Elements.

Page 34: Stacks, Queues & Recursion

44 33 11 55 77 90 40 60 99 22 88 66 Starting from the Right to Find the Number <

4422 33 11 55 77 90 40 60 99 44 88 66

From the Left to Find the Number > 4422 33 11 44 77 90 40 60 99 55 88 66

22 33 11 40 77 90 44 60 99 55 88 66

22 33 11 40 44 90 77 60 99 55 88 66 Now 44 is on its Correct Position

• We can Process only One Sub-List at a Time• Two Stacks Lower and Upper will be used

Page 35: Stacks, Queues & Recursion

• Boundary Values :– Address of the First and Last values of Sub-List

Lower 1 Upper 12Lower Empty Upper EmptyLower 1,6 Upper 4,12Lower 1,6 Upper 4,10 A[6] A[7] A[8] A[9] A[10] A[11] A[12]

90 77 60 99 55 88 6666 77 60 99 55 88 9066 77 60 90 55 88 9966 77 60 88 55 90 99 First Sub-List Second Sub-List

Page 36: Stacks, Queues & Recursion

QUICK ( A, N, BEG, END, LOC )

• A : Name of Array• N : Number of Elements• BEG : Beginning Boundary Value• END : Ending Boundary Value• LOC : Position of the First Element• Local Variables :

– LEFT– RIGHT

Page 37: Stacks, Queues & Recursion

1. [Initialize] Set LEFT := BEG, RIGHT := END and LOC := BEG2. [Scan from Right to Left]

a) Repeat while A[LOC] <= A[RIGHT]RIGHT := RIGHT – 1[End of Loop]

b) If LOC = RIGHT, then : Returnc) If [LOC] > A [RIGHT] ,then:

1) [Interchange A [LOC] and A[RIGHT] ]TEMP := A[LOC], A[LOC] = A[RIGHT],

A[RIGHT]=TEMP2) Set LOC := RIGHT3) Go to Step 3

[End of If Structure]

Page 38: Stacks, Queues & Recursion

3. [Scan from Left to Right]a) Repeat while A[LEFT] <= A[LOC]

LEFT := LEFT + 1 [End of Loop]

b) If LOC = LEFT, then : Returnc) If [LEFT] > A [LOC] ,then:

1) [Interchange A [LEFT] and A[LOC] ]TEMP := A[LOC], A[LOC] = A[LEFT],

A[LEFT]=TEMP2) Set LOC := LEFT3) Go to Step 2

[End of If Structure]

Page 39: Stacks, Queues & Recursion

1. [Initialize] TOP := 02. [PUSH Boundary values of A onto Stacks when 2 or More Elements]

If N > 1, then TOP:=TOP+1, LOWER[1]:=1, UPPER[1]:=N3. Repeat Steps 4 to 7 while TOP != 04. [Pop Sub-List from Stacks]

Set BEG := LOWER[TOP] , END := UPPER[TOP] TOP := TOP -1

5. Call QUICK (A, N, BEG, END, LOC)6. [Push Left Sub-List onto Stacks when 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 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] (Quick Sort)

Page 40: Stacks, Queues & Recursion

Reading Assignments

• Minimizing Overflowpage: 168

• Recursion 6.6

• Tower of Hanoi 6.7

• Implementation of Recursion by Stack 6.8

• Double Ended Queue DEQUES 6.10

• Priority Queues 6.11