1 / 40

Stacks, Queues & Recursion

Stacks, Queues & Recursion. Stacks: LIFO Last In First Out Queues: FIFO First In First Out. QUEUES FIFO. AAA Front DDD Rear. DDD. AAA. BBB. CCC.

phyre
Download Presentation

Stacks, Queues & Recursion

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


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

  2. QUEUES FIFO AAA Front DDD Rear DDD AAA BBB CCC • 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

  3. 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]

  4. Representation of Queues Cont… 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 FRONT-1 AAA BBB CCC DDD ……. ……. …… REAR -4 1 2 3 4 5 6 N

  5. 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

  6. (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 (a) Initially Empty FRONT-0 REAR -0 1 2 3 4 5

  7. (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 (f) F Inserted FRONT-4 F D E REAR -1 1 2 3 4 5

  8. (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 (k) K Inserted FRONT-2 G H K REAR -4 1 2 3 4 5

  9. QINSERT (QUEUE, N, FRONT, REAR, ITEM) This procedure inserts an element ITEM into a queue. • [Queue already filled?] If FRONT =1 and REAR = N, or if FRONT=REAR+1 Then write: OVERFLOW and return • [Find new value of REAR] If FRONT:=NULL [QUEUE Initially empty] Then : Set FRONT:=1 and REAR:=1 Else If REAR =N then Set REAR:=1 Else: Set REAR:=REAR+1 [End of If structure] • Set QUEUE[REAR]:=ITEM [ This inserts new element] • Return

  10. QDELETE (QUEUE, N, FRONT, REAR, ITEM) This procedure deletes an element from a queue and assigns it to the variable item. • [QUEUE already empty?] If FRONT:=NULL, then write: UNDERFLOW and Return • Set ITEM:=QUEUE[FRONT] • [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] • Return

  11. 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”

  12. Operations On Stack AAA BBB CCC FFF DDD EEE DDD EEE TOP FFF CCC BBB AAA • 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.

  13. POSTPONED DECISIONS C B B B A A A 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.

  14. 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

  15. 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)

  16. 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

  17. PUSH (STACK, TOP, MAXSTR, ITEM) • This procedure pushes an ITEM onto a stack • If TOP = MAXSTR, then Print: OVERFLOW, and Return. • Set TOP := TOP + 1 [Increases TOP by 1] • Set STACK [TOP] := ITEM. [Insert ITEM in TOP position] • Return • POP (STACK, TOP, ITEM) • This procedure deletes the top element of STACK and assign it to the variable ITEM • If TOP = 0, then Print: UNDERFLOW, and Return. • Set ITEM := STACK[TOP] • Set TOP := TOP - 1 [Decreases TOP by 1] • Return

  18. 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 / +

  19. Evaluation of Expression • The Computer Usually Evaluates an Arithmetic expression written in infix notation into steps • First converts the expression to postfix notation • 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

  20. This Algorithm Finds the VALUE of an Arithmetic Expression P Written in Postfix Notation. • Add a right parenthesis “)” at the end of P. • Scan P from left to right and repeat step 3 and 4 for each element of P until “)”is encountered. • If an operand is encountered, put it in STACK. • If an operator X is encountered then: • Remove the two top elements of STACK • Evaluate B X A • Place the result of (b) back on STACK. • [End of IF Structure] • [End of STEP2 loop] • Set VALUE equal to the top element on STACK. • Exit

  21. Stack Postfix Operation • Q: 5 * ( 6 + 2 ) – 12 / 4 • P : 5 , 6 , 2 , + , * , 12 , 4 , / , - , ) Symbol Scanned STACK • 5 5 • 6 5,6 • 2 5,6,2 • + 5,8 • * 40 • 12 40,12 • 4 40, 12, 4 • / 40, 3 • - 37 • )

  22. 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.

  23. Algorithm: POLISH (Q, P) • PUSH “(” onto STACK, and add “)” to the end of Q • Scan Q from left to right and repeat step 3 to step 6 for each element of Q until the STACK is empty. • If an operands is encountered, add it to P • If a left parenthesis is encountered, push it onto STACK • If an operator X is encountered then: • 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 • Add X to STACK [END of IF Structure] • If a right parenthesis is encountered then: • Repeatedly POP from STACK and add to P each operator (on the top of STACK) until a left parenthesis is encountered. • Remove the left parenthesis [END of IF Structure] [END of STEP 2 loop] • EXIT

  24. 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 • A ( A • + ( + A • ( ( + ( A • B ( + ( A B • * ( + ( * A B • C ( + ( * A B C • - ( + ( - A B C * • ( ( + ( - ( A B C * • D ( + ( - ( A B C * D • / ( + ( - ( / A B C * D • E ( + ( - ( / A B C * D E

  25. 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 • ( + ( - ( / A B C * D E • F ( + ( - ( / A B C * D E F • ) ( + ( - A B C * D E F / • * ( + ( - * A B C * D E F / • G ( + ( - * A B C * D E F / G • ) ( + A B C * D E F / G * - • * ( + * A B C * D E F / G * - • H ( + * A B C * D E F / G * - H • ) A B C * D E F / G * - H * + P: A B C * D E F / G * - H * +

  26. RECURSIONRecursive 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

  27. 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) !

  28. Example: Postpone Decision • 4! = 4 . 3! • 3! = 3 . 2! • 2! = 2. 1! • 1! = 1. 0! • 0! = 1 • 1! = 1.1 = 1 • 2! = 2.1 = 2 • 3! = 3.2 = 6 • 4! = 4.6 = 24

  29. 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

  30. 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

  31. 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

  32. 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 Start 1 5 4 3 2 2 3 AAA BBB CCC DDD EEE FFF GGG

  33. 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.

  34. 44 33 11 55 77 90 40 60 99 22 88 66 Starting from the Right to Find the Number < 44 22 33 11 55 77 90 40 60 99 44 88 66 From the Left to Find the Number > 44 22 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

  35. Boundary Values : • Address of the First and Last values of Sub-List Lower 1 Upper 12 Lower Empty Upper Empty Lower 1,6 Upper 4,12 Lower 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 66 66 77 60 99 55 88 90 66 77 60 90 55 88 99 66 77 60 88 55 90 99 First Sub-List Second Sub-List

  36. 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

  37. 1. [Initialize] Set LEFT := BEG, RIGHT := END and LOC := BEG 2. [Scan from Right to Left] a) Repeat while A[LOC] <= A[RIGHT] RIGHT := RIGHT – 1 [End of Loop] b) If LOC = RIGHT, then : Return c) If [LOC] > A [RIGHT] ,then: 1) [Interchange A [LOC] and A[RIGHT] ] TEMP := A[LOC], A[LOC] = A[RIGHT], A[RIGHT]=TEMP 2) Set LOC := RIGHT 3) Go to Step 3 [End of If Structure]

  38. 3. [Scan from Left to Right] a) Repeat while A[LEFT] <= A[LOC] LEFT := LEFT + 1 [End of Loop] b) If LOC = LEFT, then : Return c) If [LEFT] > A [LOC] ,then: 1) [Interchange A [LEFT] and A[LOC] ] TEMP := A[LOC], A[LOC] = A[LEFT], A[LEFT]=TEMP 2) Set LOC := LEFT 3) Go to Step 2 [End of If Structure]

  39. [Initialize] TOP := 0 • [PUSH Boundary values of A onto Stacks when 2 or More Elements] If N > 1, then TOP:=TOP+1, LOWER[1]:=1, UPPER[1]:=N • Repeat Steps 4 to 7 while TOP != 0 • [Pop Sub-List from Stacks] Set BEG := LOWER[TOP] , END := UPPER[TOP] TOP := TOP -1 • Call QUICK (A, N, BEG, END, LOC) • [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] • [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] • [Exit] (Quick Sort)

  40. Reading Assignments Minimizing Overflow page: 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

More Related