do you remember what is the most complexity?...abstract data type (adt) abstract data type = a data...

Post on 01-Aug-2020

4 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Do you remember what is the most powerful tool for managing complexity?

2

Abstraction!

Abstractions and more abstractions …

3You are here

8.1 Three views of data

4

Application or user level

Logical or abstract level

Implementation level

Abstract Data Types (ADTs)

are here!

The Data Structures from Ch.7 are here!

Applications, like spreadsheets or

robotics (Chs.12, 13, 14) are here!

Abstract Data Type (ADT)

Abstract data type = A data structure whose properties (data and operations) are specified independently of any particular implementation.

5

Python strings and lists have their own methods attached to them, e.g. my_list.sort( )

… but we do not know how exactly they are stored in

memory, or what algorithm is used for sorting!

Abstract Data Type (ADT)

An abstract data type is also called container or black-box.

6

8.2 Stacks

Stack = An ADT in which accesses are made at only one end

– LIFO = Last In First Out

– The insert is called Push and the removal is called Pop

7

Name three everyday objects that operate as stacks!

Stack example:Towers of Hanoi

8

Tower of Hanoi - Wikipedia, the free encyclopedia

9

Stack algorithmsPlacing elements in the stack:

WHILE (more data)Read valuepush(myStack, value)

Removing elements from the stack:

WHILE (NOT IsEmpty(myStack))value = pop(myStack)Write value

ExampleA stack is initially empty. Draw the stack after

each of these operations:• push(42)• push(15)• push(10)• pop()• push(21)• pop()• pop()

10

42 4215

10

4215

4215

421521

4215

42

QUIZA stack contains initially only the number 42. Draw

the stack at the end of each operation:• push(10)• push(11)• pop()• push(12)• pop()• push(101)• push(102)• pop()

11

42

Solution• push(10)• push(11)• pop()• push(12)• pop()• push(101)• push(102)• pop()

12

1011042

This is the stack at the end:

8.3 Queues

Queue = An ADT in which items are inserted at one end and removed from the other end

– FIFO = First In First Out

– No standard queue terminology

• Enqueue, Enque, Enq, Enter, and Insertare used for the insertion operation

• Dequeue, Deque, Deq, Delete, and Removeare used for the removal operation.

13

Name three

everydaystructuresthat arequeues

QUIZA queue is initially empty. Draw the queue after

each of these operations:• enque(42)• enque(15)• enque(10)• deque()• enque(21)• deque()• deque()

14

42

4215

421510

1510

Interesting trivia: queueing is one of only two words in the English language that has 5 vowels in a row!

E.g. Queueing Theory

Alternative spelling: queing

15

The other one is miaouing (miaoued?)

Queue algorithmsPlacing elements in the queue:

WHILE (more data)Read valueenque(myQueue, value)

Removing elements from the queue:

WHILE (NOT IsEmpty(myQueue))value = deque(myQueue)Write value

Two implementations for ADTsArray-based implementationObjects in the container are kept in an array, i.e. physically next to each other in memory.

Linked-based implementationObjects in the container are not kept physically together, but each item tells you where to go to get the next one in the structure

17

Did you ever play treasure hunt, a game in which each cluetells you where to go to get the next clue?

18

Memory maps forArray implementation Linked implementation

Not in text

19

Stacks and Queues in the linked implementation

20

Why access elements only at the ends?

8.4 Lists• List are more general ADTs than stacks and queues,

because operations can be performed anywhere, not just at the ends.

• There is an index for the current item (crt) that can move through the list.– Operations are performed at position crt

21

8.4 ListsNote: The text does not mention crt, but some list operations (Reset, GetNext, MoreItems) are impossible without it! (See next slide…)

22

Operations that can be applied to lists:• InsertItem Insert new item into list at position crt

– The old item moves right, crt points to new item• DeleteItem Remove the crt item from the list

– Move crt right (except when at tail of list, in which case crtpoints to the new tail)

• GetNext Get the crt item– Move crt right (if at end of list set crt = NULL)

• MoreItems Are there more items after crt?• Reset Brings crt back to head of list

23

QUIZ: Show the list and the outputs (if any) after each of the following operations:

getNext()getNext()delete()getNext()insert(42)moreItems()getNext() getNext()getNext()reset()

24

Array implementation of a list

crt

Details in COSC 2341 - Data Structures!

Note: The text does not mention crt, but some list operations (Reset, GetNext, MoreItems) are impossible without it!

1

Array implementation of a list

Big problem: insertion and deletion require shifting the “tail” of the array → time-consuming!

Do not confuse the levels!

The list (ADT, Ch.8) is here!

The array (data structure, ch.7) is

here!

The Excel spreadsheet(application, Chs.12, 13, 14)

is here!

Linked implementation of a list

28

crt

But, wait a sec, this is the same diagram we had for the list ADT – why are we calling it now an implementation?

A: Because most list implementations are actually linked!

Algorithm for creating a list and printing its elements

29

WHILE (more data)Read valueInsert(myList, value)

Reset(myList)Write "Items in the list are "WHILE (moreItems(myList))

GetNext(myList, nextItem)Write nextItem, ' 'moveNext(myList)

Brings crt back to the head of the list

Trick question: Which implementation is being used (array or linked)?

30

Logical LevelThe algorithm that uses the list does not and should not know how the data in the list is stored (array or linked), or how the various operations (Insert(), Reset(), MoreItems()) are implemented!

We have written algorithms using a stack, a queue, and a list without ever knowing the internal workings, i.e. the implementation of these ADTs/containers.

8.5 TreesADTs such as lists, stacks, and queues are used to model linear relationshipsOther types of relationships require different, non-linear ADTs.

31

Binary Tree (BT)

32

Root node

Node with two children

Node with right child

Leaf node

Node with left child

Binary tree = An ADT/container with a unique starting node called the root, in which:• A node can have 0, 1, or 2 children• A unique path (series of nodes) exists from the root to every other node

– Equivalently, there are no loops!

33

QUIZ

34

Write the (unique) path from the root to the node containing:• 7• 8• 6

QUIZ

35

List all the nodes having:• 0 children• 1 child• 2 children

QUIZ: Are these Trees? BTs?

36

QUIZ: Are these Trees? BTs?

QUIZ CONCLUSIONS: Trees• Have one (and only one) root• The edges are directional, from parent to child• There is one path from the root to any other node• The path above is unique

In addition, Binary Trees have to satisfy:• Any node can have only 0, 1, or 2 children

To do for next time:

• Read pp.247-258 in our text.• End-of-chapter 1 – 9, 11 – 19, 21 – 24

39EoHW 1

Putting a BT to work:Binary Search Tree (BST)

40

Do you notice a pattern in this BT?

Binary Search Tree = A tree with the following properties:1. Shape property → It is a binary tree2. Semantic property→ For every node, the value

stored in the node is– greater than the value in any node in its left subtree

and– smaller than the value in any node in its right subtree

41

QUIZ: Are these Binary Search Trees?

Algorithm for searching an item in a BST

43

IsThere(tree, item)IF (tree is null)

RETURN FALSEELSE

IF (item equals info(tree))RETURN TRUE

ELSEIF (item < info(tree))

IsThere(left(tree), item)ELSE

IsThere(right(tree), item)

Recursive!

Example:Search for item 18

44

IsThere(tree, item)IF (tree is null)

RETURN FALSEELSE

IF (item equals info(tree))RETURN TRUE

ELSEIF (item < info(tree))

IsThere(left(tree), item)ELSE

IsThere(right(tree), item)

Read the detailed explanation on pp.256-7!

QUIZ• What do the acronyms BT and BST mean in

Computer Science?

• How is a BT similar to a BST?

• How is a BT different from a BST?

45

Binary Search Tree = A tree with the following properties:1. Shape property → It is a binary tree2. Semantic property→ For every node, the value

stored in the node is– greater than the value in any node in its left subtree

and– smaller than the value in any node in its right subtree

46

x

<X >X

47

Inserting an item in a BST: first we have to search for it!

Search for Kyrstenin this tree …

48

Inserting an item in a BST: first we have to search for it!

Search for kyrstenin this tree …

… and insert the itemwhere the search ended!

49

Insert(tree, item)IF (tree is null)

Put item in a new treeELSE

IF (item < info(tree))Insert (left(tree), item)

ELSEInsert (right(tree), item)

Note how similar this algorithmis to the search algorithm!

QUIZ on BST insertion

Problem 47/280:The following elements are inserted in an initially empty BST:50, 72, 96, 107, 26, 12, 11, 9, 2, 10, 25, 51, 16, 17, 95Find the final tree.

50

QUIZ on BST insertion

The following strings are inserted in an initially empty BST:“Hello, world!”, “COSC 1302”, “MATH 2412”, “PHYS 2425”, “ENGL 1301”, “ENGL 1302”

Show the final tree.Hint: Use dictionary order.

51

Printing/traversing a BST

52

Print(tree)If (tree is not null)

Print (left(tree))Write info(tree)Print (right(tree))

Is that all there is to it? Yes!Remember that recursive

algorithms can be very powerful

Printing/traversing a BST

53

Print(tree)If (tree is not null)

Print (left(tree))Write info(tree)Print (right(tree))

This is called “in-order” traversal

QUIZ: Printing/traversing a BST

54

Print(tree)If (tree is not null)

Print (left(tree))Write info(tree)Print (right(tree))

Apply the algorithm to this BST. Show all output.

FYI: Other tree algorithmsFinding the depth of a tree:

Depth(tree)IF (tree is null)

RETURN 0ELSE

RETURN max(Depth(left(tree), Depth(right(tree)))

Finding the length of a tree:

Length(tree)IF (tree is null)

RETURN 0ELSE

RETURN 1 + Length(left(tree))+ Length(right(tree))

8.6 Graphs

Graph = A data structure that consists of a set of nodes (called vertices) and a set of edges that connect nodes to each other.

Note: The “unique path” condition from trees has been removed; graphs are more general than trees!

56

Graphs: Unlike trees, there can be cycles and unconnected parts

57

QUIZ: Find 5 different cycles in this graph

58

QUIZ: In each case, decide if the data structure is a tree or just a graph

59

Graphs: directed and undirected

60

Graphs

61

Representing a Graph: adjacency matrix

62

See Table 8.3/262

Our text simply calls it

“table”

QUIZ: Draw the adjacency matrix for this graph

63

QUIZ: Draw the adjacency matrix for this graph

64

QUIZ: Draw the adjacency matrix for this graph

65EOL 3

QUIZ: Draw the adjacency matrix for this graph

66

Graph Algorithms

67

Depth-First Searching Algorithm--Given a starting vertex and an ending vertex, we can develop an algorithm that finds a path from startVertex to endVertex

This is called a depth-first search because we start at a given vertex, we go to the deepest branch and explore as far down one path before taking alternative choices at earlier branches.

68

DFS – Stack to the rescue!

69

startVertex endVertex

Push the start vertex

DFS – Stack to the rescue!

70

startVertex endVertex

Pop the start vertex, then push its children (in alphabetical order)

DFS – Stack to the rescue!

Figure 8.11 Using a stack to store the routes

71

startVertex endVertex

Unleash recursion!

DFS – Nitty gritty: How to avoid loops?

Figure 8.11 Using a stack to store the routes

72

startVertex endVertex

Mark each node when we push it.

DFS – Nitty gritty: When to stop?

Figure 8.11 Using a stack to store the routes

73

startVertex endVertex

A node is considered visited when popped (not when pushed)

QUIZ DFS: Find a path from Austin to Chicago

74

Depth First Search(startVertex, endVertex)Set found to FALSEPush(myStack, startVertex)WHILE (NOT IsEmpty(myStack) AND NOT found)

Pop(myStack, tempVertex)IF (tempVertex equals endVertex)

Write endVertexSet found to TRUE

ELSE IF (tempVertex not visited)Write tempVertexPush all unvisited vertices adjacent to tempVertexMark tempVertex as visited

IF (found)Write "Path has been printed"

ELSEWrite "Path does not exist")

75

And mark pushed vertex

as visited

Is this the only path from Austin to Washington?

76

Is this the shortest path from Austin to Washington?

77

Conclusion on DFS: The algorithm is guaranteed to find a path (if at least one exists) between the given vertices• Not all paths• Not (in general) the shortest path

To find all, or the shortest path, we need to use different algorithms …

78

Other Graph Algorithms

• Breadth-First Search (BFS)• Single-Source Shortest-Path

Search (SSPS)• All-Pairs Shortest Path Search• Flow algorithms• Etc. etc. etc.

79

Skip them in our text!

80

SKIP8.7 Subprogram Statements

READ and take notes:Ethical issues: Workplace Monitoring

Homework for Ch.8

31, 32, 34, 35, 37, 38, 47, 48, 5054 →“Table” means adjacency matrix.56 → Instead of Sandler, let the destination be Fred. The edges are all bidirectional (they go both ways). Remember that we push nodes on the stack in alphabetical order!

81

Chapter Review Questions

• Distinguish between an array-based implementation and a linked implementation

• Distinguish between an array and a list• Distinguish between and a unsorted list and a sorted

list• Distinguish between the behavior of a stack and a

queue• Distinguish between the binary tree and a binary

search tree

82

Chapter Review Questions

• Draw the binary search tree that is built from inserting a series of items

• Understand the difference between a tree and a graph

• Use the DFS algorithm to find a path between two nodes of a graph.

83

top related