SlideShare a Scribd company logo
1 of 43
Lecture - 6(Stacks)
       On
  Data structures
Lecture Outline

•   What is a Stack?
•   Array implementation of stacks
•   Operations on a Stack
•   Arithmetic expressions
•   stacks are used to evaluate postfix expressions
•   Infix expressions into postfix Expressions
•   Quicksort
Stacks

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

•  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.
Diagram of stacks
    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




AAA    BBB   CCC   DDD   EEE    FFF


1        2     3     4    5      6    7     8      9   10                N-1
N
               TOP
Array implementation of stacks

•   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
Array Representation of Stacks
                                STACK

    XXX       YYY        ZZZ

    1            2        3           4        5         6          7         8

                                                   MAXSTK      8
     TOP     3



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
Operations on a Stack

Maximum size of n.

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.
These are the basic operations that can be performed on a stack.
Operations on a Stack
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.
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.

In order to understand the algorithm, let's break it apart line by line.

PUSH(STACK, TOP, MAXSTK, ITEM)

First, Push accepts a parameter - item. This parameter is of the same type as the rest
of the stack. Item is the data to be added to the stack.
 if top = MAXSTK, then stack is full.
This line performs a check to see whether or not the stack is full.

top := top+1; If the stack is not full, top is increased by a value equal to the size of
another item. This allocates room for the insertion.
Pushing
             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, then TOP=TOP+1=4
•   STACK[TOP]:= STACK[4]:= ITEM=80
•   N=5
•   MAXSTACK=10
              0    1    2     3     4       5     6    7    8   9
     STACK   17   23   97    44   80

                                        top = 4       N=5
Operations on a Stack
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.

      Procedure 6.2 POP (STACK, TOP, ITEM);
      1. If TOP = 0 then : Print :”UNDERFLOW”, and return.
      2. ITEM : =STACK[TOP]) .
      3. Set : TOP := TOP-1
      4. Return.

      If TOP = 0 then, stack is empty, there is no item to pop off the stack. Control
     can then be passed to an error handling routine.

      ITEM : =STACK[TOP]) Set item to be equal to the data in the top .

     TOP := TOP-1; This statement removes the top item from the stack.
Decrement top by 1 so that it now accesses the new top of the stack.
Poping

             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, then ITEM:=STACK[TOP]= STACK[4]= 80
•   TOP=TOP-1=3
•   N=4
•   MAXSTACK=10


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

                                            top = 3               N=4
Arithmetic expressions
•   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/D+EF

    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-D/(E+F)
Arithmetic expressions


•   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*DEF+/-
Polish Notation

Q an arithmetic expression involving constants and operations
The binary operation in Q may have different levels of precedence :

Highest :          Exponentiation(↑)
Next highest :     Multiplication(*) and division(/)
Lowest : Addition (+) and subtraction (-)
Ex :
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
Polish notation

•   Infix expressions into polish 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.
Polish notation

An example shows the ease with which a complex statement in prefix notation
   can be deciphered through order of operations:
                   - * / 15 - 7 + 1 1 3 + 2 + 1 1 =
                   - * / 15 - 7 2 3 + 2 + 1 1 =
                   - * / 15 5 3 + 2 + 1 1 =
                   -*33+2+11=
                   -9+2+11=
                    -9+22=
                    -94=
                      5
An equivalent in-fix is as follows: ((15 / (7 - (1 + 1))) * 3) - (2 + 1 + 1) = 5
Arithmetic expressions(Reverse Polish 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
Stacks are used to evaluate postfix expressions

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 6.3 : 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 steps 3 and 4 for each element of P until
    the sentinel “)” is encountered.
3. If an operand is encountered, put it on STACK.
4. If an operator x 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]
5. Set VALUE equal to the top element on STACK.
6. Exit.
Example 6.5
Postfix notation 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) )
Infix expressions into postfix Expressions

Algorithm 6.4 :
    Suppose Q is an arithmetic Expressions written in Infix notation. This algorithm finds
    the equivalent postfix expression P.
1. Push “(“ onto STACK, and add “)” to the end of Q.
2. Scan Q from left to right and repeat steps 3 to 6 for each element of Q until the
    STACK is empty.
3. If an operand is encountered, add it to P.
4. If a left parenthesis is encountered, push it onto STACK.
5. 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.
Infix expression Q: A+(B*C-(D/E F)*G)*H
Infix into postfix expression

Infix                           Postfix
2+3                             23+

2+3*6                            36*2+

(2 + 3) * 6                     23+6*

A / (B * C) + D * E - A * C      ABC*/DE*+AC*-
Quicksort
    Quicksort 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
Combine : the sorted S1 (by the time returned from
recursion), followed by v, followed by the sorted S2 (i.e.,                 S
nothing extra needs to be done)



                                                                        v
                                                                   S1               S2
Quicksort

– 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
Example

We are given array of n integers to sort:



    40      20      10     80      60       50   7   30   100
Pick Pivot Element
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
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
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 = 0          40      20     10      80      60   50   7   30 100

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

                   LEFT = 0                                   RIGHT = 8
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
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 = 0          40      20     10      80      60   50   7   30 100

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

                   LEFT = 0                                   RIGHT = 8
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
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 = 0          40      20     10      80      60   50   7   30 100

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

                   LEFT = 0                                   RIGHT = 7
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
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
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
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
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
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
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
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
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
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 = 3          30      20     10      40      60   50   7   80 100

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

                   LEFT = 3                                   RIGHT = 7
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
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 = 3          30      20     10      40      60   50   7   80 100

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

                   LEFT = 3                                   RIGHT = 6
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
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 = 6         30     20      10      7     60     50   40   80 100

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

                  LEFT = 3                                    RIGHT = 6
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
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 = 6         30     20      10      7     60     50   40   80 100

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

                  LEFT = 4                                    RIGHT = 6
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
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 = 4          30      20     10       7      40   50   60   80 100

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

                   LEFT = 4                                    RIGHT = 6
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
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 = 4          30      20     10       7      40   50   60   80 100

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

                   LEFT = 4                                    RIGHT = 5
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
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 = 4          30      20     10       7      40   50   60   80 100

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

                   LEFT = 4                                    RIGHT = 4
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
Data structure lecture7
Data structure lecture7

More Related Content

What's hot (19)

Stack - Data Structure
Stack - Data StructureStack - Data Structure
Stack - Data Structure
 
Stack Operation In Data Structure
Stack Operation In Data Structure Stack Operation In Data Structure
Stack Operation In Data Structure
 
Stacks and queues
Stacks and queuesStacks and queues
Stacks and queues
 
Lecture 6 data structures and algorithms
Lecture 6 data structures and algorithmsLecture 6 data structures and algorithms
Lecture 6 data structures and algorithms
 
STACKS IN DATASTRUCTURE
STACKS IN DATASTRUCTURESTACKS IN DATASTRUCTURE
STACKS IN DATASTRUCTURE
 
Application of Stack - Yadraj Meena
Application of Stack - Yadraj MeenaApplication of Stack - Yadraj Meena
Application of Stack - Yadraj Meena
 
Stacks in DATA STRUCTURE
Stacks in DATA STRUCTUREStacks in DATA STRUCTURE
Stacks in DATA STRUCTURE
 
Stacks and Queue - Data Structures
Stacks and Queue - Data StructuresStacks and Queue - Data Structures
Stacks and Queue - Data Structures
 
Stack Data Structure
Stack Data StructureStack Data Structure
Stack Data Structure
 
Stacks
StacksStacks
Stacks
 
Stack Data Structure V1.0
Stack Data Structure V1.0Stack Data Structure V1.0
Stack Data Structure V1.0
 
Stack application
Stack applicationStack application
Stack application
 
stacks and queues
stacks and queuesstacks and queues
stacks and queues
 
Queues-handouts
Queues-handoutsQueues-handouts
Queues-handouts
 
Stacks, Queues, Deques
Stacks, Queues, DequesStacks, Queues, Deques
Stacks, Queues, Deques
 
Stacks
StacksStacks
Stacks
 
Stack data structure
Stack data structureStack data structure
Stack data structure
 
03 stacks and_queues_using_arrays
03 stacks and_queues_using_arrays03 stacks and_queues_using_arrays
03 stacks and_queues_using_arrays
 
Stacks in Data Structure
Stacks in Data StructureStacks in Data Structure
Stacks in Data Structure
 

Similar to Data structure lecture7

Stacks,queues,linked-list
Stacks,queues,linked-listStacks,queues,linked-list
Stacks,queues,linked-listpinakspatel
 
Stacks IN DATA STRUCTURES
Stacks IN DATA STRUCTURESStacks IN DATA STRUCTURES
Stacks IN DATA STRUCTURESSowmya Jyothi
 
Stack_Overview_Implementation_WithVode.pptx
Stack_Overview_Implementation_WithVode.pptxStack_Overview_Implementation_WithVode.pptx
Stack_Overview_Implementation_WithVode.pptxchandankumar364348
 
Data structure lab manual
Data structure lab manualData structure lab manual
Data structure lab manualnikshaikh786
 
Chapter 5-stack.pptx
Chapter 5-stack.pptxChapter 5-stack.pptx
Chapter 5-stack.pptxHalid Assen
 
DS-UNIT 3 FINAL.pptx
DS-UNIT 3 FINAL.pptxDS-UNIT 3 FINAL.pptx
DS-UNIT 3 FINAL.pptxprakashvs7
 
Stack and Queue.pptx university exam preparation
Stack and Queue.pptx university exam preparationStack and Queue.pptx university exam preparation
Stack and Queue.pptx university exam preparationRAtna29
 
Data structures stacks
Data structures   stacksData structures   stacks
Data structures stacksmaamir farooq
 
Lec5-Stack-bukc-28022024-112316am (1) .pptx
Lec5-Stack-bukc-28022024-112316am (1) .pptxLec5-Stack-bukc-28022024-112316am (1) .pptx
Lec5-Stack-bukc-28022024-112316am (1) .pptxhaaamin01
 
STACK AND ITS OPERATIONS IN DATA STRUCTURES.pptx
STACK AND ITS OPERATIONS IN DATA STRUCTURES.pptxSTACK AND ITS OPERATIONS IN DATA STRUCTURES.pptx
STACK AND ITS OPERATIONS IN DATA STRUCTURES.pptxKALPANAC20
 
Chapter 5 Stack and Queue.pdf
Chapter 5 Stack and Queue.pdfChapter 5 Stack and Queue.pdf
Chapter 5 Stack and Queue.pdfGirT2
 
Stacks Data structure.pptx
Stacks Data structure.pptxStacks Data structure.pptx
Stacks Data structure.pptxline24arts
 
358 33 powerpoint-slides_9-stacks-queues_chapter-9
358 33 powerpoint-slides_9-stacks-queues_chapter-9358 33 powerpoint-slides_9-stacks-queues_chapter-9
358 33 powerpoint-slides_9-stacks-queues_chapter-9sumitbardhan
 

Similar to Data structure lecture7 (20)

Stacks,queues,linked-list
Stacks,queues,linked-listStacks,queues,linked-list
Stacks,queues,linked-list
 
Stacks IN DATA STRUCTURES
Stacks IN DATA STRUCTURESStacks IN DATA STRUCTURES
Stacks IN DATA STRUCTURES
 
Stack_Overview_Implementation_WithVode.pptx
Stack_Overview_Implementation_WithVode.pptxStack_Overview_Implementation_WithVode.pptx
Stack_Overview_Implementation_WithVode.pptx
 
Data structure lab manual
Data structure lab manualData structure lab manual
Data structure lab manual
 
Chapter 5-stack.pptx
Chapter 5-stack.pptxChapter 5-stack.pptx
Chapter 5-stack.pptx
 
U3.stack queue
U3.stack queueU3.stack queue
U3.stack queue
 
DS MOD2 (1) (1).pptx
DS MOD2 (1) (1).pptxDS MOD2 (1) (1).pptx
DS MOD2 (1) (1).pptx
 
DS-UNIT 3 FINAL.pptx
DS-UNIT 3 FINAL.pptxDS-UNIT 3 FINAL.pptx
DS-UNIT 3 FINAL.pptx
 
Stack.pptx
Stack.pptxStack.pptx
Stack.pptx
 
Unit 3 stack
Unit 3   stackUnit 3   stack
Unit 3 stack
 
Stack and Queue.pptx university exam preparation
Stack and Queue.pptx university exam preparationStack and Queue.pptx university exam preparation
Stack and Queue.pptx university exam preparation
 
Data structures stacks
Data structures   stacksData structures   stacks
Data structures stacks
 
Lec5-Stack-bukc-28022024-112316am (1) .pptx
Lec5-Stack-bukc-28022024-112316am (1) .pptxLec5-Stack-bukc-28022024-112316am (1) .pptx
Lec5-Stack-bukc-28022024-112316am (1) .pptx
 
LEC3-DS ALGO(updated).pdf
LEC3-DS  ALGO(updated).pdfLEC3-DS  ALGO(updated).pdf
LEC3-DS ALGO(updated).pdf
 
Stack
StackStack
Stack
 
STACK AND ITS OPERATIONS IN DATA STRUCTURES.pptx
STACK AND ITS OPERATIONS IN DATA STRUCTURES.pptxSTACK AND ITS OPERATIONS IN DATA STRUCTURES.pptx
STACK AND ITS OPERATIONS IN DATA STRUCTURES.pptx
 
Unit 3 stack
Unit   3 stackUnit   3 stack
Unit 3 stack
 
Chapter 5 Stack and Queue.pdf
Chapter 5 Stack and Queue.pdfChapter 5 Stack and Queue.pdf
Chapter 5 Stack and Queue.pdf
 
Stacks Data structure.pptx
Stacks Data structure.pptxStacks Data structure.pptx
Stacks Data structure.pptx
 
358 33 powerpoint-slides_9-stacks-queues_chapter-9
358 33 powerpoint-slides_9-stacks-queues_chapter-9358 33 powerpoint-slides_9-stacks-queues_chapter-9
358 33 powerpoint-slides_9-stacks-queues_chapter-9
 

More from Kumar

Graphics devices
Graphics devicesGraphics devices
Graphics devicesKumar
 
Fill area algorithms
Fill area algorithmsFill area algorithms
Fill area algorithmsKumar
 
region-filling
region-fillingregion-filling
region-fillingKumar
 
Bresenham derivation
Bresenham derivationBresenham derivation
Bresenham derivationKumar
 
Bresenham circles and polygons derication
Bresenham circles and polygons dericationBresenham circles and polygons derication
Bresenham circles and polygons dericationKumar
 
Introductionto xslt
Introductionto xsltIntroductionto xslt
Introductionto xsltKumar
 
Extracting data from xml
Extracting data from xmlExtracting data from xml
Extracting data from xmlKumar
 
Xml basics
Xml basicsXml basics
Xml basicsKumar
 
XML Schema
XML SchemaXML Schema
XML SchemaKumar
 
Publishing xml
Publishing xmlPublishing xml
Publishing xmlKumar
 
Applying xml
Applying xmlApplying xml
Applying xmlKumar
 
Introduction to XML
Introduction to XMLIntroduction to XML
Introduction to XMLKumar
 
How to deploy a j2ee application
How to deploy a j2ee applicationHow to deploy a j2ee application
How to deploy a j2ee applicationKumar
 
JNDI, JMS, JPA, XML
JNDI, JMS, JPA, XMLJNDI, JMS, JPA, XML
JNDI, JMS, JPA, XMLKumar
 
EJB Fundmentals
EJB FundmentalsEJB Fundmentals
EJB FundmentalsKumar
 
JSP and struts programming
JSP and struts programmingJSP and struts programming
JSP and struts programmingKumar
 
java servlet and servlet programming
java servlet and servlet programmingjava servlet and servlet programming
java servlet and servlet programmingKumar
 
Introduction to JDBC and JDBC Drivers
Introduction to JDBC and JDBC DriversIntroduction to JDBC and JDBC Drivers
Introduction to JDBC and JDBC DriversKumar
 
Introduction to J2EE
Introduction to J2EEIntroduction to J2EE
Introduction to J2EEKumar
 

More from Kumar (20)

Graphics devices
Graphics devicesGraphics devices
Graphics devices
 
Fill area algorithms
Fill area algorithmsFill area algorithms
Fill area algorithms
 
region-filling
region-fillingregion-filling
region-filling
 
Bresenham derivation
Bresenham derivationBresenham derivation
Bresenham derivation
 
Bresenham circles and polygons derication
Bresenham circles and polygons dericationBresenham circles and polygons derication
Bresenham circles and polygons derication
 
Introductionto xslt
Introductionto xsltIntroductionto xslt
Introductionto xslt
 
Extracting data from xml
Extracting data from xmlExtracting data from xml
Extracting data from xml
 
Xml basics
Xml basicsXml basics
Xml basics
 
XML Schema
XML SchemaXML Schema
XML Schema
 
Publishing xml
Publishing xmlPublishing xml
Publishing xml
 
DTD
DTDDTD
DTD
 
Applying xml
Applying xmlApplying xml
Applying xml
 
Introduction to XML
Introduction to XMLIntroduction to XML
Introduction to XML
 
How to deploy a j2ee application
How to deploy a j2ee applicationHow to deploy a j2ee application
How to deploy a j2ee application
 
JNDI, JMS, JPA, XML
JNDI, JMS, JPA, XMLJNDI, JMS, JPA, XML
JNDI, JMS, JPA, XML
 
EJB Fundmentals
EJB FundmentalsEJB Fundmentals
EJB Fundmentals
 
JSP and struts programming
JSP and struts programmingJSP and struts programming
JSP and struts programming
 
java servlet and servlet programming
java servlet and servlet programmingjava servlet and servlet programming
java servlet and servlet programming
 
Introduction to JDBC and JDBC Drivers
Introduction to JDBC and JDBC DriversIntroduction to JDBC and JDBC Drivers
Introduction to JDBC and JDBC Drivers
 
Introduction to J2EE
Introduction to J2EEIntroduction to J2EE
Introduction to J2EE
 

Recently uploaded

Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsAndrey Dotsenko
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Science&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfScience&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfjimielynbastida
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxnull - The Open Security Community
 

Recently uploaded (20)

Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Science&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfScience&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdf
 
The transition to renewables in India.pdf
The transition to renewables in India.pdfThe transition to renewables in India.pdf
The transition to renewables in India.pdf
 
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort ServiceHot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
 

Data structure lecture7

  • 1. Lecture - 6(Stacks) On Data structures
  • 2. Lecture Outline • What is a Stack? • Array implementation of stacks • Operations on a Stack • Arithmetic expressions • stacks are used to evaluate postfix expressions • Infix expressions into postfix Expressions • Quicksort
  • 3. Stacks • 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. • 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.
  • 4. Diagram of stacks 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 AAA BBB CCC DDD EEE FFF 1 2 3 4 5 6 7 8 9 10 N-1 N TOP
  • 5. Array implementation of stacks • 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
  • 6. Array Representation of Stacks STACK XXX YYY ZZZ 1 2 3 4 5 6 7 8 MAXSTK 8 TOP 3 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
  • 7. Operations on a Stack Maximum size of n. 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. These are the basic operations that can be performed on a stack.
  • 8. Operations on a Stack 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. 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. In order to understand the algorithm, let's break it apart line by line. PUSH(STACK, TOP, MAXSTK, ITEM) First, Push accepts a parameter - item. This parameter is of the same type as the rest of the stack. Item is the data to be added to the stack. if top = MAXSTK, then stack is full. This line performs a check to see whether or not the stack is full. top := top+1; If the stack is not full, top is increased by a value equal to the size of another item. This allocates room for the insertion.
  • 9. Pushing 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, then TOP=TOP+1=4 • STACK[TOP]:= STACK[4]:= ITEM=80 • N=5 • MAXSTACK=10 0 1 2 3 4 5 6 7 8 9 STACK 17 23 97 44 80 top = 4 N=5
  • 10. Operations on a Stack 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. Procedure 6.2 POP (STACK, TOP, ITEM); 1. If TOP = 0 then : Print :”UNDERFLOW”, and return. 2. ITEM : =STACK[TOP]) . 3. Set : TOP := TOP-1 4. Return. If TOP = 0 then, stack is empty, there is no item to pop off the stack. Control can then be passed to an error handling routine. ITEM : =STACK[TOP]) Set item to be equal to the data in the top . TOP := TOP-1; This statement removes the top item from the stack. Decrement top by 1 so that it now accesses the new top of the stack.
  • 11. Poping 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, then ITEM:=STACK[TOP]= STACK[4]= 80 • TOP=TOP-1=3 • N=4 • MAXSTACK=10 0 1 2 3 4 5 6 7 8 9 STACK 17 23 97 44 top = 3 N=4
  • 12. Arithmetic expressions • 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/D+EF 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-D/(E+F)
  • 13. Arithmetic expressions • 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*DEF+/-
  • 14. Polish Notation Q an arithmetic expression involving constants and operations The binary operation in Q may have different levels of precedence : Highest : Exponentiation(↑) Next highest : Multiplication(*) and division(/) Lowest : Addition (+) and subtraction (-) Ex : 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
  • 15. Polish notation • Infix expressions into polish 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.
  • 16. Polish notation An example shows the ease with which a complex statement in prefix notation can be deciphered through order of operations: - * / 15 - 7 + 1 1 3 + 2 + 1 1 = - * / 15 - 7 2 3 + 2 + 1 1 = - * / 15 5 3 + 2 + 1 1 = -*33+2+11= -9+2+11= -9+22= -94= 5 An equivalent in-fix is as follows: ((15 / (7 - (1 + 1))) * 3) - (2 + 1 + 1) = 5
  • 17. Arithmetic expressions(Reverse Polish 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
  • 18. Stacks are used to evaluate postfix expressions 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 6.3 : 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 steps 3 and 4 for each element of P until the sentinel “)” is encountered. 3. If an operand is encountered, put it on STACK. 4. If an operator x 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] 5. Set VALUE equal to the top element on STACK. 6. Exit.
  • 19. Example 6.5 Postfix notation 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) )
  • 20. Infix expressions into postfix Expressions Algorithm 6.4 : Suppose Q is an arithmetic Expressions written in Infix notation. This algorithm finds the equivalent postfix expression P. 1. Push “(“ onto STACK, and add “)” to the end of Q. 2. Scan Q from left to right and repeat steps 3 to 6 for each element of Q until the STACK is empty. 3. If an operand is encountered, add it to P. 4. If a left parenthesis is encountered, push it onto STACK. 5. 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.
  • 21. Infix expression Q: A+(B*C-(D/E F)*G)*H
  • 22. Infix into postfix expression Infix Postfix 2+3 23+ 2+3*6 36*2+ (2 + 3) * 6 23+6* A / (B * C) + D * E - A * C ABC*/DE*+AC*-
  • 23. Quicksort Quicksort 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 Combine : the sorted S1 (by the time returned from recursion), followed by v, followed by the sorted S2 (i.e., S nothing extra needs to be done) v S1 S2
  • 24. Quicksort – 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
  • 25. Example We are given array of n integers to sort: 40 20 10 80 60 50 7 30 100
  • 26. Pick Pivot Element 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
  • 27. 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 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 = 0 40 20 10 80 60 50 7 30 100 [0] [1] [2] [3] [4] [5] [6] [7] [8] LEFT = 0 RIGHT = 8
  • 28. 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 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 = 0 40 20 10 80 60 50 7 30 100 [0] [1] [2] [3] [4] [5] [6] [7] [8] LEFT = 0 RIGHT = 8
  • 29. 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 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 = 0 40 20 10 80 60 50 7 30 100 [0] [1] [2] [3] [4] [5] [6] [7] [8] LEFT = 0 RIGHT = 7
  • 30. 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 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
  • 31. 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 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
  • 32. 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 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
  • 33. 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 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
  • 34. 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 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 = 3 30 20 10 40 60 50 7 80 100 [0] [1] [2] [3] [4] [5] [6] [7] [8] LEFT = 3 RIGHT = 7
  • 35. 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 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 = 3 30 20 10 40 60 50 7 80 100 [0] [1] [2] [3] [4] [5] [6] [7] [8] LEFT = 3 RIGHT = 6
  • 36. 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 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 = 6 30 20 10 7 60 50 40 80 100 [0] [1] [2] [3] [4] [5] [6] [7] [8] LEFT = 3 RIGHT = 6
  • 37. 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 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 = 6 30 20 10 7 60 50 40 80 100 [0] [1] [2] [3] [4] [5] [6] [7] [8] LEFT = 4 RIGHT = 6
  • 38. 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 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 = 4 30 20 10 7 40 50 60 80 100 [0] [1] [2] [3] [4] [5] [6] [7] [8] LEFT = 4 RIGHT = 6
  • 39. 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 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 = 4 30 20 10 7 40 50 60 80 100 [0] [1] [2] [3] [4] [5] [6] [7] [8] LEFT = 4 RIGHT = 5
  • 40. 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 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 = 4 30 20 10 7 40 50 60 80 100 [0] [1] [2] [3] [4] [5] [6] [7] [8] LEFT = 4 RIGHT = 4
  • 41. 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