58
CS341 PASCAL II - Data Structures 1 PASCAL II - Data PASCAL II - Data Structures Structures Philip Fees CS341

CS341 PASCAL II - Data Structures1 PASCAL II - Data Structures Philip Fees CS341

  • View
    224

  • Download
    0

Embed Size (px)

Citation preview

Page 1: CS341 PASCAL II - Data Structures1 PASCAL II - Data Structures Philip Fees CS341

CS341 PASCAL II - Data Structures

1

PASCAL II - Data StructuresPASCAL II - Data Structures

Philip Fees

CS341

Page 2: CS341 PASCAL II - Data Structures1 PASCAL II - Data Structures Philip Fees CS341

CS341 PASCAL II - Data Structures

2

Introduction Introduction

What will be studied?– Data Types– Arrays– Records– Abstract Data– Pointers– Linked lists, Stacks, Queues

What is a data structure?

Page 3: CS341 PASCAL II - Data Structures1 PASCAL II - Data Structures Philip Fees CS341

CS341 PASCAL II - Data Structures

3

Workshop 1Workshop 1

File I/O Concepts Pascal File I/O User Defined Types

Page 4: CS341 PASCAL II - Data Structures1 PASCAL II - Data Structures Philip Fees CS341

CS341 PASCAL II - Data Structures

4

File I/O ConceptsFile I/O Concepts

Generally termed Device I/O– Could be hard disk, CD-ROM, tape, etc.– Could be terminal, socket (IPC/Internet), etc.

Delimited files (whitespace, eol, eof) vs. non delimited

Encoded (ASCII, EBCDIC) vs. binary Open and Close Read or write via file/device handle (symbolic name) Seek vs. non-seek devices Sequential vs. Indexed

Page 5: CS341 PASCAL II - Data Structures1 PASCAL II - Data Structures Philip Fees CS341

CS341 PASCAL II - Data Structures

5

Pascal File I/O - HandlesPascal File I/O - Handles

Identify handle (symbolic name)Program myProgram (input, output, fileHandle);

VARfileHandle : text;

Associate file to handle– “create procedure file prior to compiling and

running the program”– TP: assign(fileHandle,’myTextFile.txt’);

Page 6: CS341 PASCAL II - Data Structures1 PASCAL II - Data Structures Philip Fees CS341

CS341 PASCAL II - Data Structures

6

Pascal File I/O - Open & Seek

Open the filereset(fileHandle);

rewind is part of “seeking” delimiter tests

WHILE not eol DO

WHILE not eol(fileHandle) DO

WHILE not eof DO

WHILE not eof(fileHandle) DO

Page 7: CS341 PASCAL II - Data Structures1 PASCAL II - Data Structures Philip Fees CS341

CS341 PASCAL II - Data Structures

7

Pascal File I/O - Read & Write

Read from file via handlereadln(fileHandle, variable1, variable2, …);

Write to file via handlewriteln(fileHandle, ‘this is a test’, variable1, …);

Ease old file contentsrewrite(fileHandle);

See example pg. 444

Page 8: CS341 PASCAL II - Data Structures1 PASCAL II - Data Structures Philip Fees CS341

CS341 PASCAL II - Data Structures

8

Exercises

Pg. 448 25 - 30

Page 9: CS341 PASCAL II - Data Structures1 PASCAL II - Data Structures Philip Fees CS341

CS341 PASCAL II - Data Structures

9

User Defined TypesUser Defined Types

Characteristic of a data type (int, char, boolean)– set of value– fixed amount of memory

Ordinal data type have pred() and succ() values

User defined a.k.a. enumerated data type

Page 10: CS341 PASCAL II - Data Structures1 PASCAL II - Data Structures Philip Fees CS341

CS341 PASCAL II - Data Structures

10

Enumerated Data TypeEnumerated Data Type

SyntaxType

Weekday = (Mon, Tues, Wed, Thur, Fri);

UsageVAR

Day : Weekday;

Day := Mon;

if (Day = Mon) then

Page 11: CS341 PASCAL II - Data Structures1 PASCAL II - Data Structures Philip Fees CS341

CS341 PASCAL II - Data Structures

11

SubrangesSubranges

Define one type as subset of another type Examples

TYPEUSYears = 1776..1998;

Days = (Sun, Mon, Tues, Wed, Thur, Fri, Sat);

Weekdays = Mon..Fri;

Operations: succ() and pred()

Page 12: CS341 PASCAL II - Data Structures1 PASCAL II - Data Structures Philip Fees CS341

CS341 PASCAL II - Data Structures

12

ExercisesExercises

Pg. 454-455 # 2, 15 Pg. 461 #22-26 Pg. 465 #8, 20, 21, 22

Page 13: CS341 PASCAL II - Data Structures1 PASCAL II - Data Structures Philip Fees CS341

CS341 PASCAL II - Data Structures

13

Workshop 2Workshop 2

Single Dimensional Arrays Selection Sort Arrays and Subroutines Searching Arrays

Page 14: CS341 PASCAL II - Data Structures1 PASCAL II - Data Structures Philip Fees CS341

CS341 PASCAL II - Data Structures

14

ArraysArrays

Collection of data elements Data elements are the same type Contiguous in memory Access individuals by subscript Array size determined by:

element size * number of elements

Page 15: CS341 PASCAL II - Data Structures1 PASCAL II - Data Structures Philip Fees CS341

CS341 PASCAL II - Data Structures

15

Pascal ArraysPascal Arrays

name : ARRAY [ index type ] OF type; Example 1:

VAR

List : ARRAY [1..5] OF integer;

Example 2:TYPE

Numbers = ARRAY [1..5] OF integer;

VAR

List : Numbers;

Page 16: CS341 PASCAL II - Data Structures1 PASCAL II - Data Structures Philip Fees CS341

CS341 PASCAL II - Data Structures

16

Pascal Arrays (cont.)Pascal Arrays (cont.)

index type alternativesTYPE

DAYS = (SUN, MON, TUES, WED, THUR, FRI, SAT);

VAR

StockPriceList : ARRAY [9..16] OF real;

NegativeList : ARRAY [-2..3] OF char;

HoursWorked : ARRAY [MON..FRI] of real;

Page 17: CS341 PASCAL II - Data Structures1 PASCAL II - Data Structures Philip Fees CS341

CS341 PASCAL II - Data Structures

17

Use of ConstantsUse of Constants

Good PraticeCONST

ClassSize = 35;

Type

TestScores = 0..100;

VAR

Score : ARRAY [1..ClassSize] of TestScores;

Page 18: CS341 PASCAL II - Data Structures1 PASCAL II - Data Structures Philip Fees CS341

CS341 PASCAL II - Data Structures

18

Arrays and LoopsArrays and Loops

“Looping” over the array Example:

FOR J := 1 to ClassSize DO

BEGINwrite(‘next: ‘);

readln(Score[J]);

writeln(‘value = ‘, Score[J]);

END

Page 19: CS341 PASCAL II - Data Structures1 PASCAL II - Data Structures Philip Fees CS341

CS341 PASCAL II - Data Structures

19

ReviewReview

Example 10.7 pg. 491 Example 10.9 pg. 493 Example 10.10 pg. 494

Page 20: CS341 PASCAL II - Data Structures1 PASCAL II - Data Structures Philip Fees CS341

CS341 PASCAL II - Data Structures

20

Selection SortSelection Sort

Sorting a list of values Algorithm

– start with first element [1] (current)– find smallest element in array and

exchange with current– current := next array element (current + 1)– continue to end of array

What is the best and worst case?

Page 21: CS341 PASCAL II - Data Structures1 PASCAL II - Data Structures Philip Fees CS341

CS341 PASCAL II - Data Structures

21

Arrays and SubroutinesArrays and Subroutines

See GetData example on pg. 508 Call by value vs. call by reference

– Call by value: create a copy of the array– Call by reference: refer to the passed array– Performance implications

Page 22: CS341 PASCAL II - Data Structures1 PASCAL II - Data Structures Philip Fees CS341

CS341 PASCAL II - Data Structures

22

Search AlgorithmsSearch Algorithms

Sequential Search (pg. 526)– search entire array until value located or

“hit” the end of the array– Average of N iterations of loop

Binary Search (pg. 528)– Assumes sorted array– start in middle; look in upper or lower half– Average of log N iterations of loop

Page 23: CS341 PASCAL II - Data Structures1 PASCAL II - Data Structures Philip Fees CS341

CS341 PASCAL II - Data Structures

23

AnalysisAnalysis

Overhead of inserting new value in sorted array

What should maximum size of the array be?

When should an array be used?

Page 24: CS341 PASCAL II - Data Structures1 PASCAL II - Data Structures Philip Fees CS341

CS341 PASCAL II - Data Structures

24

ExercisesExercises

Arrays: pp. 497-500 # 1-5, 10, 20 Sorts: pg. 507 # 2, 3, 6 Subroutines: pg. 516 # 16-19 Searching: pg. #533 5, 15

Page 25: CS341 PASCAL II - Data Structures1 PASCAL II - Data Structures Philip Fees CS341

CS341 PASCAL II - Data Structures

25

Workshop 3Workshop 3

Multi-dimensional arrays

Page 26: CS341 PASCAL II - Data Structures1 PASCAL II - Data Structures Philip Fees CS341

CS341 PASCAL II - Data Structures

26

Array in MemoryArray in Memory

Array stored in contiguous memory Location is calculated:

– Starting address + (row index * # of columns) + column index

Row Major vs. Column Major

Page 27: CS341 PASCAL II - Data Structures1 PASCAL II - Data Structures Philip Fees CS341

CS341 PASCAL II - Data Structures

27

Pascal SyntaxPascal Syntax

Syntax<name> : ARRAY [ <row index>, <column

index> ] OF <element type>

Page 28: CS341 PASCAL II - Data Structures1 PASCAL II - Data Structures Philip Fees CS341

CS341 PASCAL II - Data Structures

28

Two Dimensional ExampleTwo Dimensional Example

Example 1:VAR

Table : ARRAY [ 1..3, 1.. 4 ] OF integer; Example 2:

TYPE

Maxtrix = [ 1.. 3, 1.. 4] OF integer;

VAR

Table : Matrix;

Page 29: CS341 PASCAL II - Data Structures1 PASCAL II - Data Structures Philip Fees CS341

CS341 PASCAL II - Data Structures

29

IterationIteration

Example:FOR row := 1 to 3 DO

FOR column := 1 to 4 DO

writeln(‘Table[‘,row,’, ‘, column,’] = ‘, Table[row][column]);

Page 30: CS341 PASCAL II - Data Structures1 PASCAL II - Data Structures Philip Fees CS341

CS341 PASCAL II - Data Structures

30

Higher Dimensional ArraysHigher Dimensional Arrays

Syntax<identifier> : ARRAY [ A1 .. B1, A2 .. B2, …,

An .. Bn] OF <type> Example1:

cube : ARRAY [ 1..3, 1..4, 1..5] OF integer; Example 2:

cube : ARRAY [ 1..3 ] OF ARRAY [ 1..4, 1..5 ] OF integer;

Page 31: CS341 PASCAL II - Data Structures1 PASCAL II - Data Structures Philip Fees CS341

CS341 PASCAL II - Data Structures

31

ExercisesExercises

pg. 567 # 4, 9-12, 13-15

Page 32: CS341 PASCAL II - Data Structures1 PASCAL II - Data Structures Philip Fees CS341

CS341 PASCAL II - Data Structures

32

Workshop 4Workshop 4

Records Variants Binary Files

Page 33: CS341 PASCAL II - Data Structures1 PASCAL II - Data Structures Philip Fees CS341

CS341 PASCAL II - Data Structures

33

Workshop 5Workshop 5

Sets

Page 34: CS341 PASCAL II - Data Structures1 PASCAL II - Data Structures Philip Fees CS341

CS341 PASCAL II - Data Structures

34

Defining and DeclaringDefining and Declaring

SyntaxTYPE

<type name> = SET OF <base type> ;

VAR

<variable name> : <type name> ;

ExampleTYPE

Digits = SET OF 0..9;

VAR

numbers : Digits;

Page 35: CS341 PASCAL II - Data Structures1 PASCAL II - Data Structures Philip Fees CS341

CS341 PASCAL II - Data Structures

35

Different than SubtypesDifferent than Subtypes

Assignmentnumbers := [ 0, 2, 4, 6, 8 ];

Set is undefined until assignment Assigned values must be in base type -

elements of the set Universal sets contain all values Subsets - one set contains all members of

another set See set definitions on top of page 735.

Page 36: CS341 PASCAL II - Data Structures1 PASCAL II - Data Structures Philip Fees CS341

CS341 PASCAL II - Data Structures

36

Set OperationsSet Operations

Union: A + B Intersection: A * B Difference: A - B

Page 37: CS341 PASCAL II - Data Structures1 PASCAL II - Data Structures Philip Fees CS341

CS341 PASCAL II - Data Structures

37

Relational OperatorsRelational Operators

equal: A = B sets A and B are identical not equal: A <> B set A and B are not

identical subset: A <= B A is a subset of B superset A >= B A is a superset of B

(A<=B)

Page 38: CS341 PASCAL II - Data Structures1 PASCAL II - Data Structures Philip Fees CS341

CS341 PASCAL II - Data Structures

38

MembershipMembership

Syntax<element> IN <set>

Example2 IN numbers

Boolean value: is 2 in the numbers set?

Page 39: CS341 PASCAL II - Data Structures1 PASCAL II - Data Structures Philip Fees CS341

CS341 PASCAL II - Data Structures

39

Membership ExampleMembership Example

Useful for “edit checks” Example

IF response IN [‘Y’, ‘y’] THEN(continue action here)

ELSE(alternative action here)

Review example on page 744.

Page 40: CS341 PASCAL II - Data Structures1 PASCAL II - Data Structures Philip Fees CS341

CS341 PASCAL II - Data Structures

40

ExercisesExercises

Page 739 # 9-15, 26-30 Page 743 # 2, 7-20, 27 Programming Problem Page 759 # 1, 3

Page 41: CS341 PASCAL II - Data Structures1 PASCAL II - Data Structures Philip Fees CS341

CS341 PASCAL II - Data Structures

41

Workshop 6Workshop 6

Model Builder Abstract Data Type (ADT) String ADT Linked List ADT

Page 42: CS341 PASCAL II - Data Structures1 PASCAL II - Data Structures Philip Fees CS341

CS341 PASCAL II - Data Structures

42

Model BuilderModel Builder

Model, design, or abstraction - analysis without being concern for details

Examples– World Wide Web– Windows– Virus– UNIX: parent process, child process, kill,

fork, etc.

Page 43: CS341 PASCAL II - Data Structures1 PASCAL II - Data Structures Philip Fees CS341

CS341 PASCAL II - Data Structures

43

Abstract Data TypeAbstract Data Type

collection of data (objects) shared properties shared operations Examples: Array, Integers,

Page 44: CS341 PASCAL II - Data Structures1 PASCAL II - Data Structures Philip Fees CS341

CS341 PASCAL II - Data Structures

44

ADT Example - StringADT Example - String

definition - finite sequence of characters terminated with null character access individual elements (substring) Operations: create, read, write, assign, length reconsider operations if string is defined by

length not null terminator.

Page 45: CS341 PASCAL II - Data Structures1 PASCAL II - Data Structures Philip Fees CS341

CS341 PASCAL II - Data Structures

45

ADT Example - Linked ListADT Example - Linked List

Definition - list of data items associated by a link to one or more nodes.

Typically point to next node (single linked) or previous node (double linked)

Head node is first node in list To “walk” the list, must start at head and

proceed sequentially. Task: Define operations, define interfaces,

implement

Page 46: CS341 PASCAL II - Data Structures1 PASCAL II - Data Structures Philip Fees CS341

CS341 PASCAL II - Data Structures

46

Workshop 7Workshop 7

Linked Lists Array Implementation of Linked Lists Pointers Pointer Implementation of Linked Lists

Page 47: CS341 PASCAL II - Data Structures1 PASCAL II - Data Structures Philip Fees CS341

CS341 PASCAL II - Data Structures

47

Why Linked ListsWhy Linked Lists

Arrays– Size fixed at Compile Time, inefficient space

utilization– Inserting, deleting, organizing are costly. Why?

Requirement– Size determined at Run Time– Minimal cost to insert, delete, and organize data

Examples– Sorting, data with undetermined number of items

Page 48: CS341 PASCAL II - Data Structures1 PASCAL II - Data Structures Philip Fees CS341

CS341 PASCAL II - Data Structures

48

Linked ListsLinked Lists

Diagram data structure (See page 872) Define operations (See page 881) Define implementation base data

structures (See page 873) Diagram operation’s effect on sample

data structure (See page 887)

Page 49: CS341 PASCAL II - Data Structures1 PASCAL II - Data Structures Philip Fees CS341

CS341 PASCAL II - Data Structures

49

Introduction to PointersIntroduction to Pointers

A pointer doesn’t contain the data, but contains a way of locating the data.

Example: Array subscriptpointer : integer

data : array [1..100] of char;

pointer := 5;

writeln(array[pointer]);

Page 50: CS341 PASCAL II - Data Structures1 PASCAL II - Data Structures Philip Fees CS341

CS341 PASCAL II - Data Structures

50

Array Implementation of Linked Array Implementation of Linked ListsLists

Issues– Still have compile time limit on number of nodes,

wasted space– Which nodes are “free”

Benefits– Simple base data type– Ok if max nodes know at compile time– Still have benefits of low cost insert, update, and

organize

Page 51: CS341 PASCAL II - Data Structures1 PASCAL II - Data Structures Philip Fees CS341

CS341 PASCAL II - Data Structures

51

Array Implementation (cont.)Array Implementation (cont.)

Free nodes– Mark all free node - sequential search– Keep linked list of free nodes

Book has special procedures to handle free nodes

Modify linked list procedures to handle free linked list– Move InitializeSpace logic into Create Procedure– Pass InsertNode the data in place of the pointer P

Page 52: CS341 PASCAL II - Data Structures1 PASCAL II - Data Structures Philip Fees CS341

CS341 PASCAL II - Data Structures

52

Pointers & Dynamic MemoryPointers & Dynamic Memory

Declaring a pointer (see page 874)Var

intPtr : ^integer;

Allocate memorynew(intPtr);

Access and deallocate memoryintPtr^ := 10;

writeln(intPtr^);

dispose(intPtr^);

Page 53: CS341 PASCAL II - Data Structures1 PASCAL II - Data Structures Philip Fees CS341

CS341 PASCAL II - Data Structures

53

Pointers & Dynamic MemoryPointers & Dynamic Memory

Declaring a pointer (see page 874)Var

intPtr : ^integer;

Allocate memorynew(intPtr);

Access and deallocate memoryintPtr^ := 10;

writeln(intPtr^);

dispose(intPtr^);

Page 54: CS341 PASCAL II - Data Structures1 PASCAL II - Data Structures Philip Fees CS341

CS341 PASCAL II - Data Structures

54

Pointers & Dynamic MemoryPointers & Dynamic Memory

Declaring a pointer (see page 874)Var

intPtr : ^integer;

Allocate memorynew(intPtr);

Access and deallocate memoryintPtr^ := 10;writeln(intPtr^);dispose(intPtr);

Page 55: CS341 PASCAL II - Data Structures1 PASCAL II - Data Structures Philip Fees CS341

CS341 PASCAL II - Data Structures

55

Pointers & Dynamic Memory Pointers & Dynamic Memory (cont.)(cont.)

NIL value - doesn’t point to anything Memory allocated by new comes from heap Must deallocate via dispose Must keep track of all allocated memory -

memory leaks

Page 56: CS341 PASCAL II - Data Structures1 PASCAL II - Data Structures Philip Fees CS341

CS341 PASCAL II - Data Structures

56

Pointer Implementation of Linked Pointer Implementation of Linked ListsLists

See page 889

Page 57: CS341 PASCAL II - Data Structures1 PASCAL II - Data Structures Philip Fees CS341

CS341 PASCAL II - Data Structures

57

Variations on Linked ListVariations on Linked List

Dummy Header - avoid test for empty list

Circularly Linked - no NIL Doubly Linked List - don’t need previous

node

Page 58: CS341 PASCAL II - Data Structures1 PASCAL II - Data Structures Philip Fees CS341

CS341 PASCAL II - Data Structures

58

ExercisesExercises

Pg 872 # 16 Pg 880 # 9-19