Stacks, Queues & Recursion Stacks: LIFO Last In First Out Queues: FIFO First In First Out 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 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] Representation of Queues Cont… FRONT-1 AAA BBB CCC DDD ……. ……. …… REAR -4 1 2 3 4 5 6 N FRONT-2 REAR -4 1 BBB CCC DDD ……. ……. …… 2 3 4 5 6 N FRONT-2 REAR -6 1 BBB CCC DDD EEE FFF …… 2 3 4 5 6 N FRONT-3 REAR -6 1 CCC DDD EEE FFF …… 3 4 5 6 N 2 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 (a) Initially Empty FRONT-0 REAR -0 1 2 3 4 5 (b) A,B,C Inserted FRONT-1 A B REAR -3 1 2 C 3 4 5 (c) A Deleted FRONT-2 B REAR - 3 1 2 C 3 4 5 (d) D and then E Inserted FRONT-2 B REAR - 5 1 2 C D E 3 4 5 (e) B and C Deleted FRONT-4 REAR - 5 1 2 3 D E 4 5 (f) F Inserted (g) D Deleted FRONT-4 F REAR -1 1 FRONT-5 F REAR -1 1 3 D E 4 5 3 4 E 5 4 E 5 G H 2 3 4 5 2 2 (h) G and then H Inserted FRONT-5 F G H REAR -3 1 2 3 (i) FRONT-1 F REAR -3 1 (j) E Deleted F Deleted FRONT-2 REAR -3 G H 1 2 3 4 5 (k) K Inserted (l) G and H Deleted FRONT-2 REAR -4 G H 1 2 3 K 4 5 5 5 FRONT-4 REAR -4 1 2 K 3 4 (m) K Deleted FRONT-0 Queue Empty REAR -0 1 2 3 4 QINSERT (QUEUE, N, FRONT, REAR, ITEM) This procedure inserts an element ITEM into a queue. 1. [Queue already filled?] If FRONT =1 and REAR = N, or if FRONT=REAR+1 Then write: OVERFLOW and return 2. [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] 3. Set QUEUE[REAR]:=ITEM [ This inserts new element] 4. Return QDELETE (QUEUE, N, FRONT, REAR, ITEM) This procedure deletes an element from a queue and assigns it to the variable item. 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 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 “PUSHDOWN” 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 AAA BBB • This means: – EEE cannot be deleted before FFF is deleted, – DDD cannot be deleted before EEE and FFF is deleted and so on. CCC FFF DDD EEE EEE DDD FFF TOP CCC BBB AAA 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. BB A A C B A Operation Of Stack • CreateStack (Size) – – – – – Function: Input: Precondition: Output: Post condition: Initialize Stack to an Empty State None None Stack Stack is Empty • DestroyStack(Stack) – – – – Function: Input: Precondition: Output: – Post condition: Remove all the Elements from Stack Stack Stack has been created Stack Stack is Empty Operation Of Stack Cont…. • EmptyStack (Stack) – – – – Function: Input: Precondition: Output: Test whether stack is Empty Stack Stack has been created EmptyStack (Boolean) • FullStack(Stack) – Function: – Input: – Precondition: Test whether stack is Full Stack Stack has been created – Output: FullStack (Boolean) Operation Of Stack Cont…. • Push (Stack, NewValue) – – – – – Function: Input: Precondition: Output: Post condition: Add new value in a Stack Stack, New Value Stack has been created and not Full Stack New Value will be added in the Stack New Top will be assigned • Pop(Stack, PoppedValue) – – – – Function: Input: Precondition: Output: – Post condition: Remove the top value from the Stack Stack Stack has been created and not Empty Stack, Popped Value New Top will be assigned • 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 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 / + 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 [+AB]*C=*+AB A+(B*C) A+[*BC]=+A*BC (A+B)/(C–D) [+ AB] / [- CD] = / + AB-CD • This Algorithm Finds the VALUE of an Arithmetic Expression P Written in Postfix Notation. 1. 2. 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: a) Remove the two top elements of STACK b) Evaluate B X A c) 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 3. 4. 5. 6. 7. 8. Stack Postfix Operation • • Q: P: 5 * ( 6 + 2 ) – 12 / 4 5 , 6 , 2 , + , * , 12 , 4 , / , - , ) Symbol Scanned 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 5 6 2 + * 12 4 / ) STACK 5 5,6 5,6,2 5,8 40 40,12 40, 12, 4 40, 3 37 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. 1. 2. 3. 4. 5. 6. 7. 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: 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] 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] EXIT 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 (+( AB (5) * (+(* AB (6) C (+(* ABC (7) (+(ABC * (8) ( (+(- ( ABC * (9) D (+(- ( ABC *D (10) / (+(- (/ ABC *D (11) E (+(- (/ ABC *DE 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 (12) (13) F (14) ) (15) * (16) G (17) ) (18) * (19) H (20) ) P: STACK (+(- (/ (+(- (/ (+((+(-* (+(-* (+ (+* (+* Expression P ABC *DE ABC *DEF ABC *DEF ABC *DEF ABC *DEF ABC *DEF ABC *DEF ABC *DEF ABC *DEF ABC *DEF /G*-H*+ / / /G /G*/G*/G*-H /G*-H*+ 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 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) ! • Example: Postpone Decision 1 2 3 4 5 6 7 8 9 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 • FACTORIAL (FACT,N) 1 2 3 4 If N = 0 then Set FACT = 1 and Return Set FACT := 1 [Initialize FACT for loop] Repeat for K = 1 to N Set FACT := K * FACT [End of Loop] 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 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 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 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 AAA 1 BBB DDD 2 3 CCC EEE GGG 3 4 2 FFF 5 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. 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 • Boundary Values : – Address of the First and Last values of Sub-List Lower 1 Lower Empty Lower 1,6 Lower 1,6 Upper 12 Upper Empty Upper 4,12 Upper 4,10 A[6] A[7] A[8] A[9] A[10] A[11] A[12] 90 77 60 99 55 66 77 60 99 55 66 77 60 90 55 66 77 60 88 55 First Sub-List 88 88 88 90 66 90 99 99 Second Sub-List 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 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] 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] 1. [Initialize] TOP := 0 2. [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 3. Repeat Steps 4 to 7 while TOP != 0 4. [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) 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