The interaction between algorithm and data structure

  • Recall:

    • Computer program = algorithm + data structure(s)

  • Algorithms can produce and consume information in different ways:

    • Some algorithms consume the data in the same order as how the data was produced

        Production  order:   A  B  C  D
        Consumption order:   A  B  C  D

    • Some algorithms consume the data in the reverse order as was produced:

        Production  order:   A  B  C  D
        Consumption order:   D  C  B  A

    • Etc, etc

Intro to the stack data structure

  • There are 2 commonly used data structures in computer science:

    1. Stack     (LIFO)
    2. Queue    (FIFO)

    We will study the stack first...

  • The stack data structure:

    • A stack is a data structure that organize the stored data in a Last In First Out (LIFO) manner

  • To achieve the LIFO behavior, the stack only provide the following 2 methods to access the data stored in a stack:

    • push(x): add x to the "top" of the stack

    • pop(): remove the item at the "top" of the stack and return it.

Analogy for the stack data structure

  • A stack data structure is like a stack of books:

Analogy for the stack data structure

  • The push operation will "insert"/add an item on top of the stack:

Analogy for the stack data structure

  • The pop operation will remove the item at the top of the stack and returns it.

  • Notice that the item removed by pop( ) is always the last item that was pushed

    The stack enforces the Last One In is the First One Out (LIFO) behavior

Some computer algorithms/processes with a natural LIFO behavior

  • Method invocation /return:

    • If the order of method invocation is:

        M1() --> M2() --> M3() --> M4() 

    • Then the order in which the methods return from their invocation is the reverse order:

        M4() --> M3() --> M2() --> M1() 

  • In CS 255, you will learn more about the System Stack maintained by the run time system that is used to store the parameter variables and the local variables of the method invocations

DEMO: 09-stack/10-call-stack/Demo.java

Some computer algorithms/processes with a natural LIFO behavior

  • The undo algorithm in a text editor:

    • If the order of changes you made to a text file is:

        M1() --> M2() --> M3() --> M4() 

    • Then the order in which the changes are undone will occur in the reverse order:

        M4() --> M3() --> M2() --> M1() 

  • This means that the text editor will use a stack to store the history of edit changes to implement its undo algorithm