chapter 2 arrays and structures the array as an abstract data type structures and unions the...

65
Chapter 2 Arrays and Chapter 2 Arrays and Structures Structures The array as an abstract data The array as an abstract data type type Structures and Unions Structures and Unions The polynomial Abstract Data Type The polynomial Abstract Data Type The Sparse Matrix Abstract Data The Sparse Matrix Abstract Data Type Type The Representation of The Representation of Multidimensional Arrays Multidimensional Arrays

Upload: patrick-rose

Post on 13-Jan-2016

250 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: Chapter 2 Arrays and Structures  The array as an abstract data type  Structures and Unions  The polynomial Abstract Data Type  The Sparse Matrix Abstract

Chapter 2 Arrays and StructuresChapter 2 Arrays and Structures

The array as an abstract data typeThe array as an abstract data type Structures and UnionsStructures and Unions The polynomial Abstract Data TypeThe polynomial Abstract Data Type The Sparse Matrix Abstract Data TypeThe Sparse Matrix Abstract Data Type The Representation of Multidimensional The Representation of Multidimensional

ArraysArrays

Page 2: Chapter 2 Arrays and Structures  The array as an abstract data type  Structures and Unions  The polynomial Abstract Data Type  The Sparse Matrix Abstract

2.1 The array as an ADT (1/6)2.1 The array as an ADT (1/6) ArraysArrays

Array: a set of pairs, <Array: a set of pairs, <index, valueindex, value>> data structuredata structure

For each index, there is a value associated with For each index, there is a value associated with that index.that index.

representation (possible)representation (possible) Implemented by using consecutive memory.Implemented by using consecutive memory. In mathematical terms, we call this a In mathematical terms, we call this a

correspondencecorrespondence or a or a mappingmapping..

Page 3: Chapter 2 Arrays and Structures  The array as an abstract data type  Structures and Unions  The polynomial Abstract Data Type  The Sparse Matrix Abstract

2.1 The array as an ADT (2/6)2.1 The array as an ADT (2/6) When considering an ADT we are more When considering an ADT we are more

concerned with the operations that can be concerned with the operations that can be performed on an array.performed on an array. Aside from Aside from creatingcreating a new array, most languages a new array, most languages

provide only two standard operations for arrays, one provide only two standard operations for arrays, one that that retrievesretrieves a value, and a second that a value, and a second that storesstores a a value.value.

Structure 2.1 shows a definition of the array ADTStructure 2.1 shows a definition of the array ADT The advantage of this ADT definition is that it clearly The advantage of this ADT definition is that it clearly

points out the fact that the array is a more general points out the fact that the array is a more general structure than “a consecutive set of memory structure than “a consecutive set of memory locations.”locations.”

Page 4: Chapter 2 Arrays and Structures  The array as an abstract data type  Structures and Unions  The polynomial Abstract Data Type  The Sparse Matrix Abstract

2.1 The array as an ADT (3/6)2.1 The array as an ADT (3/6)

Page 5: Chapter 2 Arrays and Structures  The array as an abstract data type  Structures and Unions  The polynomial Abstract Data Type  The Sparse Matrix Abstract

2.1 The array as an ADT (4/6)2.1 The array as an ADT (4/6) Arrays in CArrays in C

int list[5], *plist[5];int list[5], *plist[5]; list[5]: (five integers) list[0], list[1], list[2], list[3], list[4]list[5]: (five integers) list[0], list[1], list[2], list[3], list[4] *plist[5]: (five pointers to integers)*plist[5]: (five pointers to integers)

plist[0], plist[1], plist[2], plist[3], plist[4]plist[0], plist[1], plist[2], plist[3], plist[4]

implementation of 1-D arrayimplementation of 1-D arraylist[0]list[0] base address = base address = list[1]list[1] + sizeof(int) + sizeof(int)list[2]list[2] + 2*sizeof(int) + 2*sizeof(int)list[3]list[3] + 3*sizeof(int) + 3*sizeof(int)list[4]list[4] + 4*sizeof(int) + 4*sizeof(int)

Page 6: Chapter 2 Arrays and Structures  The array as an abstract data type  Structures and Unions  The polynomial Abstract Data Type  The Sparse Matrix Abstract

2.1 The array as an ADT (5/6)2.1 The array as an ADT (5/6)

Arrays in C (cont’d)Arrays in C (cont’d) Compare Compare int *list1int *list1 and and int list2[5]int list2[5] in C. in C.

Same:Same: list1 and list2 are list1 and list2 are pointers.pointers.Difference:Difference: list2 reserves list2 reserves five locations.five locations.

Notations:Notations:list2list2 - - a pointer to list2[0]a pointer to list2[0](list2 + i)(list2 + i) - - a pointer to list2[i] a pointer to list2[i] (&list2[i])(&list2[i])*(list2 + i)*(list2 + i) - - list2[i]list2[i]

Page 7: Chapter 2 Arrays and Structures  The array as an abstract data type  Structures and Unions  The polynomial Abstract Data Type  The Sparse Matrix Abstract

2.1 The array (6/6)2.1 The array (6/6) Example: Example:

1-dimension array addressing1-dimension array addressing int one[] = {0, 1, 2, 3, 4};int one[] = {0, 1, 2, 3, 4}; Goal: print out address and valueGoal: print out address and value

void print1(int *ptr, int rows){void print1(int *ptr, int rows){/* print out a one-dimensional array using a pointer *//* print out a one-dimensional array using a pointer */

int i;int i;printf(“Address Contents\n”);printf(“Address Contents\n”);for (i=0; i < rows; i++)for (i=0; i < rows; i++)

printf(“%8u%5d\n”, printf(“%8u%5d\n”, ptr+iptr+i, , *(ptr+i)*(ptr+i)););printf(“\n”);printf(“\n”);

}}

Address Contents

1228 0

1230 1

1232 2

1234 3

1236 4

Page 8: Chapter 2 Arrays and Structures  The array as an abstract data type  Structures and Unions  The polynomial Abstract Data Type  The Sparse Matrix Abstract

2.2 Structures and Unions (1/6)2.2 Structures and Unions (1/6)

2.2.1 Structures (records)2.2.1 Structures (records) Arrays are collections of data of the same type. In C Arrays are collections of data of the same type. In C

there is an alternate way of grouping data that permit there is an alternate way of grouping data that permit the data to vary in type.the data to vary in type. This mechanism is called the This mechanism is called the structstruct, short for structure., short for structure.

A structure is a collection of data items, where each A structure is a collection of data items, where each item is identified as to its type and name.item is identified as to its type and name.

Page 9: Chapter 2 Arrays and Structures  The array as an abstract data type  Structures and Unions  The polynomial Abstract Data Type  The Sparse Matrix Abstract

2.2 Structures and Unions (2/6)2.2 Structures and Unions (2/6)

Create structure data typeCreate structure data type We can create our own structure data types by using We can create our own structure data types by using

the the typedeftypedef statement as below: statement as below:

This says that human_being is the name of the type defined This says that human_being is the name of the type defined by the structure definition, and we may follow this definition by the structure definition, and we may follow this definition with declarations of variables such as:with declarations of variables such as:

human_being person1, person2;human_being person1, person2;

Page 10: Chapter 2 Arrays and Structures  The array as an abstract data type  Structures and Unions  The polynomial Abstract Data Type  The Sparse Matrix Abstract

2.2 Structures and Unions (3/6)2.2 Structures and Unions (3/6) We can also embed a structure within a structure.We can also embed a structure within a structure.

A person born on February 11, 1994, would have have A person born on February 11, 1994, would have have values for the values for the datedate structstruct set as set as

Page 11: Chapter 2 Arrays and Structures  The array as an abstract data type  Structures and Unions  The polynomial Abstract Data Type  The Sparse Matrix Abstract

2.2 Structures and Unions (4/6)2.2 Structures and Unions (4/6) 2.2.2 Unions2.2.2 Unions

A A unionunion declaration is similar to a structure. declaration is similar to a structure. The fields of a The fields of a unionunion must share their memory space. must share their memory space. Only one field of the Only one field of the unionunion is “active” at any given time is “active” at any given time

Example: Add fields for male and female.

person1.sex_info.sex = male;person1.sex_info.u.beard = FALSE;andperson2.sex_info.sex = female;person2.sex_info.u.children = 4;

Page 12: Chapter 2 Arrays and Structures  The array as an abstract data type  Structures and Unions  The polynomial Abstract Data Type  The Sparse Matrix Abstract

2.2 Structures and Unions (5/6)2.2 Structures and Unions (5/6)

2.2.3 Internal implementation of structures2.2.3 Internal implementation of structures The fields of a structure in memory will be stored in The fields of a structure in memory will be stored in

the same way using increasing address locations in the same way using increasing address locations in the order specified in the structure definition.the order specified in the structure definition.

Holes or padding may actually occurHoles or padding may actually occur Within a structure to permit two consecutive components to Within a structure to permit two consecutive components to

be properly aligned within memorybe properly aligned within memory

The size of an object of a struct or union type is the The size of an object of a struct or union type is the amount of storage necessary to represent the largest amount of storage necessary to represent the largest component, including any padding that may be component, including any padding that may be required.required.

Page 13: Chapter 2 Arrays and Structures  The array as an abstract data type  Structures and Unions  The polynomial Abstract Data Type  The Sparse Matrix Abstract

2.2 Structures and Unions (6/6)2.2 Structures and Unions (6/6) 2.2.4 Self-Referential Structures2.2.4 Self-Referential Structures

One or more of its components is a pointer to itself.One or more of its components is a pointer to itself.

typedef struct list {typedef struct list {char data;char data;list *link;list *link;}}

list item1, item2, item3;list item1, item2, item3;item1.data=‘a’;item1.data=‘a’;item2.data=‘b’;item2.data=‘b’;item3.data=‘c’;item3.data=‘c’;item1.link=item2.link=item3.link=NULL;item1.link=item2.link=item3.link=NULL;

a b c

Construct a list with three nodesitem1.link=&item2;item2.link=&item3;malloc: obtain a node (memory)free: release memory

Page 14: Chapter 2 Arrays and Structures  The array as an abstract data type  Structures and Unions  The polynomial Abstract Data Type  The Sparse Matrix Abstract

2.3 The polynomial ADT (1/10)2.3 The polynomial ADT (1/10)

Ordered or Linear List ExamplesOrdered or Linear List Examples ordered (linear) listordered (linear) list: (item1, item2, item3, …, item: (item1, item2, item3, …, itemnn))

(Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, (Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday)Saturday)

(Ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King)(Ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King) (basement, lobby, mezzanine, first, second)(basement, lobby, mezzanine, first, second) (1941, 1942, 1943, 1944, 1945)(1941, 1942, 1943, 1944, 1945) (a(a11, a, a22, a, a33, …, a, …, an-1n-1, a, ann))

Page 15: Chapter 2 Arrays and Structures  The array as an abstract data type  Structures and Unions  The polynomial Abstract Data Type  The Sparse Matrix Abstract

2.3 The polynomial ADT (2/10)2.3 The polynomial ADT (2/10) Operations on Ordered ListOperations on Ordered List

Finding Finding the length, the length, nn , of the list. , of the list. ReadingReading the items from left to right (or right to left). the items from left to right (or right to left). RetrievingRetrieving the the ii’th element.’th element. StoringStoring a new value into the i’th position. a new value into the i’th position. InsertingInserting a new element at the position a new element at the position ii , causing , causing

elements numbered elements numbered ii, , ii+1, …, +1, …, nn to become numbered to become numbered ii+1, +1, ii+2, …, +2, …, nn+1+1

DeletingDeleting the element at position the element at position ii , causing elements , causing elements numbered numbered ii+1, …, +1, …, nn to become numbered to become numbered ii, , ii+1, …, +1, …, nn-1-1

ImplementationImplementation sequential mapping (1)~(4)sequential mapping (1)~(4) non-sequential mapping (5)~(6) non-sequential mapping (5)~(6)

Page 16: Chapter 2 Arrays and Structures  The array as an abstract data type  Structures and Unions  The polynomial Abstract Data Type  The Sparse Matrix Abstract

2.3 The polynomial ADT (3/10)2.3 The polynomial ADT (3/10)

Polynomial examples:Polynomial examples: Two example polynomials are:Two example polynomials are:

AA((xx) = 3) = 3xx2020+2+2xx55+4 and +4 and BB((xx) = ) = xx44+10+10xx33+3+3xx22+1+1 Assume that we have two polynomials, Assume that we have two polynomials,

AA(x) = (x) = aaiixxii and and BB((xx) = ) = bbiixxii where x is the variable, ai is the coefficient, and i is the exponent, then:then: AA((xx) + ) + BB((xx) = ) = ((aaii + + bbii))xxii

AA((xx) · ) · BB((xx) = ) = ((aaiixxii · · ((bbjjxxjj)))) Similarly, we can define subtraction and division on Similarly, we can define subtraction and division on

polynomials, as well as many other operations.polynomials, as well as many other operations.

Page 17: Chapter 2 Arrays and Structures  The array as an abstract data type  Structures and Unions  The polynomial Abstract Data Type  The Sparse Matrix Abstract

2.3 The polynomial ADT (4/10)2.3 The polynomial ADT (4/10)

An ADT definition An ADT definition of a polynomialof a polynomial

Page 18: Chapter 2 Arrays and Structures  The array as an abstract data type  Structures and Unions  The polynomial Abstract Data Type  The Sparse Matrix Abstract

2.3 The polynomial ADT (5/10)2.3 The polynomial ADT (5/10) There are two ways to create the type There are two ways to create the type

polynomialpolynomial in C in C Representation IRepresentation I

define MAX_degree 101 /*MAX degree of polynomial+1*/define MAX_degree 101 /*MAX degree of polynomial+1*/typedef struct{typedef struct{

int degree;int degree;float coef [MAX_degree];float coef [MAX_degree];

}polynomial;}polynomial;drawback: the firstrepresentation may

waste space.

Page 19: Chapter 2 Arrays and Structures  The array as an abstract data type  Structures and Unions  The polynomial Abstract Data Type  The Sparse Matrix Abstract

2.3 (6/10)2.3 (6/10) Polynomial AdditionPolynomial Addition /* d =a + b, where a, b, and d are polynomials *//* d =a + b, where a, b, and d are polynomials */

d = Zero( )d = Zero( )while (! IsZero(a) && ! IsZero(b)) do {while (! IsZero(a) && ! IsZero(b)) do { switch COMPARE (Lead_Exp(a), Lead_Exp(b)) { switch COMPARE (Lead_Exp(a), Lead_Exp(b)) { case -1: d = case -1: d = Attach(d, Coef (b, Lead_Exp(b)), Lead_Exp(b)); Attach(d, Coef (b, Lead_Exp(b)), Lead_Exp(b)); b = Remove(b, Lead_Exp(b)); b = Remove(b, Lead_Exp(b)); break; break; case 0: sum = Coef (a, Lead_Exp (a)) + Coef ( b, Lead_Exp(b)); case 0: sum = Coef (a, Lead_Exp (a)) + Coef ( b, Lead_Exp(b)); if (sum) { if (sum) { Attach (d, sum, Lead_Exp(a)); Attach (d, sum, Lead_Exp(a)); } } a = Remove(a , Lead_Exp(a)); a = Remove(a , Lead_Exp(a)); b = Remove(b , Lead_Exp(b)); b = Remove(b , Lead_Exp(b)); break; break; case 1: d = case 1: d = Attach(d, Coef (a, Lead_Exp(a)), Lead_Exp(a)); Attach(d, Coef (a, Lead_Exp(a)), Lead_Exp(a)); a = Remove(a, Lead_Exp(a)); a = Remove(a, Lead_Exp(a)); } } }}insert any remaining terms of a or b into d insert any remaining terms of a or b into d

**Program 2.4 :Program 2.4 :Initial version ofInitial version of padd padd function(p.62)function(p.62)

advantage: easy implementationdisadvantage: waste space when sparse

Page 20: Chapter 2 Arrays and Structures  The array as an abstract data type  Structures and Unions  The polynomial Abstract Data Type  The Sparse Matrix Abstract

2.3 The polynomial ADT (7/10)2.3 The polynomial ADT (7/10)

Representation IIRepresentation II MAX_TERMS 100 /*size of terms array*/MAX_TERMS 100 /*size of terms array*/

typedef struct{typedef struct{float coef;float coef;int expon;int expon;

}polynomial;}polynomial;polynomial terms [MAX_TERMS];polynomial terms [MAX_TERMS];int avail = 0;int avail = 0;

Page 21: Chapter 2 Arrays and Structures  The array as an abstract data type  Structures and Unions  The polynomial Abstract Data Type  The Sparse Matrix Abstract

2.3 The polynomial ADT (8/10)2.3 The polynomial ADT (8/10) Use one global array to store all polynomialsUse one global array to store all polynomials

Figure 2.2 shows how these polynomials are Figure 2.2 shows how these polynomials are stored in the array stored in the array termsterms..

A(x) = 2x1000+1B(x) = x4+10x3+3x2+1

specification representationpoly <start, finish>A <0,1>B <2,5>

storage requirements: start, finish, 2*(finish-start+1)non-sparse: twice as much as Representation I when all the items are nonzero

Page 22: Chapter 2 Arrays and Structures  The array as an abstract data type  Structures and Unions  The polynomial Abstract Data Type  The Sparse Matrix Abstract

2.3 The polynomial ADT (9/10)2.3 The polynomial ADT (9/10) We would now like to We would now like to

write a C function that write a C function that adds two polynomials, adds two polynomials, AA and and BB, represented , represented as above to obtain as above to obtain DD = = AA + + BB.. To produce To produce DD((xx)),, paddpadd

(Program 2.5) adds (Program 2.5) adds AA((xx) ) and and BB((xx) term by term.) term by term.

Analysis: O(n+m)where n (m) is the number of nonzeros in A (B).

Page 23: Chapter 2 Arrays and Structures  The array as an abstract data type  Structures and Unions  The polynomial Abstract Data Type  The Sparse Matrix Abstract

2.3 The polynomial ADT (10/10)2.3 The polynomial ADT (10/10)

Problem: Compaction is requiredwhen polynomials that are no longer needed.(data movement takes time.)

Page 24: Chapter 2 Arrays and Structures  The array as an abstract data type  Structures and Unions  The polynomial Abstract Data Type  The Sparse Matrix Abstract

2.4 The sparse matrix ADT (1/18)2.4 The sparse matrix ADT (1/18) 2.4.1 Introduction2.4.1 Introduction

In mathematics, a matrix contains In mathematics, a matrix contains mm rows and rows and nn columns of elements, we write columns of elements, we write mmnn to to designate a matrix with designate a matrix with mm rows and rows and nn columns. columns.

5*3

6*615/15 8/36

sparse matrixdata structure?

Page 25: Chapter 2 Arrays and Structures  The array as an abstract data type  Structures and Unions  The polynomial Abstract Data Type  The Sparse Matrix Abstract

2.4 2.4 The sparse matrix ADT (2/18)The sparse matrix ADT (2/18)

The standard representation of a matrix is a two The standard representation of a matrix is a two dimensional array defined as dimensional array defined as aa[[MAX_ROWSMAX_ROWS]][[MAX_COLSMAX_COLS].]. We can locate quickly any element by writing We can locate quickly any element by writing aa[[i i ][ ][ j j ]]

Sparse matrix wastes spaceSparse matrix wastes space We must consider alternate forms of representation.We must consider alternate forms of representation. Our representation of sparse matrices should store only Our representation of sparse matrices should store only

nonzero elements.nonzero elements. Each element is characterized by <row, col, value>.

Page 26: Chapter 2 Arrays and Structures  The array as an abstract data type  Structures and Unions  The polynomial Abstract Data Type  The Sparse Matrix Abstract

2.4 2.4 The sparse matrix ADT (3/18)The sparse matrix ADT (3/18)

Structure 2.3 Structure 2.3 contains our contains our specification of specification of the matrix ADT.the matrix ADT. A minimal set of A minimal set of

operations operations includes matrix includes matrix creation, addition, creation, addition, multiplication, multiplication, and transpose.and transpose.

Page 27: Chapter 2 Arrays and Structures  The array as an abstract data type  Structures and Unions  The polynomial Abstract Data Type  The Sparse Matrix Abstract

2.4 2.4 The sparse matrix ADT (4/18)The sparse matrix ADT (4/18)

We implement the We implement the CreateCreate operation as operation as below:below:

Page 28: Chapter 2 Arrays and Structures  The array as an abstract data type  Structures and Unions  The polynomial Abstract Data Type  The Sparse Matrix Abstract

2.4 2.4 The sparse matrix ADT (5/18)The sparse matrix ADT (5/18) Figure 2.4(a) shows how the sparse matrix of Figure Figure 2.4(a) shows how the sparse matrix of Figure

2.3(b) is represented in the array 2.3(b) is represented in the array aa.. Represented by a two-dimensional array.Represented by a two-dimensional array. Each element is characterized by Each element is characterized by <row, col, value>.<row, col, value>.

transpose

row, column in ascending order

# of rows (columns) # of nonzero terms

Page 29: Chapter 2 Arrays and Structures  The array as an abstract data type  Structures and Unions  The polynomial Abstract Data Type  The Sparse Matrix Abstract

2.4 2.4 The sparse matrix ADT (6/18)The sparse matrix ADT (6/18) 2.4.2 Transpose a Matrix2.4.2 Transpose a Matrix

For each For each rowrow i i take element <i, j, value> and store it in element <j, i, value> of take element <i, j, value> and store it in element <j, i, value> of

the transpose.the transpose. difficulty: difficulty: where to put <j, i, value>where to put <j, i, value>

((0, 00, 0, 15) ====> (, 15) ====> (0, 00, 0, 15), 15)((0, 30, 3, 22) ====> (, 22) ====> (3, 03, 0, 22), 22)((0, 50, 5, -15) ====> (, -15) ====> (5, 05, 0, -15), -15)((1, 11, 1, 11) ====> (, 11) ====> (1, 11, 1, 11), 11)Move elements down very often.Move elements down very often.

For all elements in For all elements in columncolumn j, j, place element <i, j, value> in element <j, i, value>place element <i, j, value> in element <j, i, value>

Page 30: Chapter 2 Arrays and Structures  The array as an abstract data type  Structures and Unions  The polynomial Abstract Data Type  The Sparse Matrix Abstract

2.4 2.4 The sparse matrix ADT (7/18)The sparse matrix ADT (7/18) This algorithm is incorporated in transpose This algorithm is incorporated in transpose

(Program 2.7).(Program 2.7).

Scan the array “columns” times.The array has “elements” elements.

==> O(columns*elements)

elementscolumns

Page 31: Chapter 2 Arrays and Structures  The array as an abstract data type  Structures and Unions  The polynomial Abstract Data Type  The Sparse Matrix Abstract

2.4 2.4 The sparse matrix ADT (8/18)The sparse matrix ADT (8/18) Discussion:Discussion: compared with 2-D array compared with 2-D array

representationrepresentation O(columns*elements)O(columns*elements) vs. O(columns*rows) vs. O(columns*rows) elements --> columns * rows when non-sparse,elements --> columns * rows when non-sparse,

O(columnsO(columns22*rows)*rows)

Problem:Problem: Scan the array “columns” times. Scan the array “columns” times. In fact, we can transpose a matrix represented as a In fact, we can transpose a matrix represented as a

sequence of triples in O(columns + elements) time.sequence of triples in O(columns + elements) time.

Solution:Solution: First, determine the number of elements First, determine the number of elements

in each column of the original matrix. in each column of the original matrix. Second, determine the starting positions of each row Second, determine the starting positions of each row

in the transpose matrix.in the transpose matrix.

Page 32: Chapter 2 Arrays and Structures  The array as an abstract data type  Structures and Unions  The polynomial Abstract Data Type  The Sparse Matrix Abstract

2.4 2.4 The sparse matrix ADT (9/18)The sparse matrix ADT (9/18) Compared with 2-D array representation:

O(columns+elements) vs. O(columns*rows) elements --> columns * rows O(columns*rows)

columns

columns

elements

elements

Cost:Additional row_terms and starting_pos arrays are required.Let the two arrays row_terms and starting_pos be shared.

columns

Page 33: Chapter 2 Arrays and Structures  The array as an abstract data type  Structures and Unions  The polynomial Abstract Data Type  The Sparse Matrix Abstract

2.4 2.4 The sparse matrix ADT (10/18)The sparse matrix ADT (10/18) After the execution of the third After the execution of the third forfor loop, the loop, the

values of values of row_termsrow_terms and and starting_posstarting_pos are: are:

transpose

[0] [1] [2] [3] [4] [0] [1] [2] [3] [4] [5][5]

row_terms = 2row_terms = 2 1 2 2 0 11 2 2 0 1starting_pos = 1 3 4 6 8 8starting_pos = 1 3 4 6 8 8

Page 34: Chapter 2 Arrays and Structures  The array as an abstract data type  Structures and Unions  The polynomial Abstract Data Type  The Sparse Matrix Abstract

2.4 2.4 The sparse matrix ADT (11/18)The sparse matrix ADT (11/18) 2.4.3 Matrix multiplication2.4.3 Matrix multiplication

Definition:Definition: Given Given AA and and BB where where AA is is mmnn and and BB is is nnpp, the , the

product matrix product matrix DD has dimension has dimension mmpp. Its <. Its <ii, , jj> > element is element is

for 0 for 0 ii < < mm and 0 and 0 jj < < pp..

Example:Example:

1

0

n

kkjikij bad

Page 35: Chapter 2 Arrays and Structures  The array as an abstract data type  Structures and Unions  The polynomial Abstract Data Type  The Sparse Matrix Abstract

2.4 2.4 The sparse matrix ADT (12/18)The sparse matrix ADT (12/18)

Sparse Matrix MultiplicationSparse Matrix Multiplication Definition: [Definition: [DD]]m*pm*p=[=[AA]]m*nm*n* [* [BB]]n*pn*p

Procedure: Fix a row of A and find all elements Procedure: Fix a row of A and find all elements in columnin column j j of of BB for for jj=0, 1, …, =0, 1, …, pp-1.-1.

Alternative 1.Alternative 1.Scan all of Scan all of BB to find all elements in to find all elements in j j..

Alternative 2.Alternative 2.Compute the transpose of Compute the transpose of BB. . (Put all column elements consecutively)(Put all column elements consecutively) Once we have located the elements of row Once we have located the elements of row ii of of AA and column and column

jj of of BB we just do a merge operation similar to that used in the we just do a merge operation similar to that used in the polynomial addition of 2.2polynomial addition of 2.2

Page 36: Chapter 2 Arrays and Structures  The array as an abstract data type  Structures and Unions  The polynomial Abstract Data Type  The Sparse Matrix Abstract

2.4 2.4 The sparse matrix ADT (13/18)The sparse matrix ADT (13/18)

General case:General case:

dij=ai0*b0j+ai1*b1j+…+ai(n-1)*b(n-1)j

Array A is grouped by i, and after transpose, array B is also grouped by j

a Sa d Sdb Sb e Sec Sc f Sf

g Sg

The generation at most:entries ad, ae, af, ag, bd, be, bf, bg, cd, ce, cf, cg

Page 37: Chapter 2 Arrays and Structures  The array as an abstract data type  Structures and Unions  The polynomial Abstract Data Type  The Sparse Matrix Abstract

The sparse matrix ADT (14/18)The sparse matrix ADT (14/18)

An ExampleAn ExampleA = 1 0 2 BT = 3 -1 0 B = 3 0 2 -1 4 6 0 0 0 -1 0 0 2 0 5 0 0 5

a[0] 2 3 5 bt[0] 3 3 4 b[0] 3 3 4

[1] 0 0 1 bt[1] 0 0 3 b[1] 0 0 3

[2] 0 2 2 bt[2] 0 1 -1 b[2] 0 2 2

[3] 1 0 -1 bt[3] 2 0 2 b[3] 1 0 -1

[4] 1 1 4 bt[4] 2 2 5 b[4] 2 2 5 [5] 1 2 6

row row rowcol col colvalue value value

Page 38: Chapter 2 Arrays and Structures  The array as an abstract data type  Structures and Unions  The polynomial Abstract Data Type  The Sparse Matrix Abstract

2.4 2.4 The sparse matrix ADT (15/18)The sparse matrix ADT (15/18) The programs 2.9 and 2.10 can obtain the product matrix The programs 2.9 and 2.10 can obtain the product matrix

DD which multiplies matrices which multiplies matrices AA and and BB..

a × b

Page 39: Chapter 2 Arrays and Structures  The array as an abstract data type  Structures and Unions  The polynomial Abstract Data Type  The Sparse Matrix Abstract

2.4 2.4 The sparse matrix ADT (16/18)The sparse matrix ADT (16/18)

Page 40: Chapter 2 Arrays and Structures  The array as an abstract data type  Structures and Unions  The polynomial Abstract Data Type  The Sparse Matrix Abstract

2.4 2.4 The sparse matrix ADT (17/18)The sparse matrix ADT (17/18) Analyzing the algorithmAnalyzing the algorithm

cols_b * termsrow1 + totalb +cols_b * termsrow1 + totalb +cols_b * termsrow2 + totalb +cols_b * termsrow2 + totalb +… +… +cols_b * termsrowp + totalbcols_b * termsrowp + totalb= cols_b * (termsrow1 + termsrow2 + … + termsrowp)+= cols_b * (termsrow1 + termsrow2 + … + termsrowp)+rows_a * totalbrows_a * totalb= cols_b * totala + row_a * totalb= cols_b * totala + row_a * totalb

O(cols_b * totala + rows_a * totalb)O(cols_b * totala + rows_a * totalb)

Page 41: Chapter 2 Arrays and Structures  The array as an abstract data type  Structures and Unions  The polynomial Abstract Data Type  The Sparse Matrix Abstract

2.4 2.4 The sparse matrix ADT (18/18)The sparse matrix ADT (18/18) Compared with matrix multiplication using arrayCompared with matrix multiplication using array

for (i =0; i < rows_a; i++)for (i =0; i < rows_a; i++) for (j=0; j < cols_b; j++) { for (j=0; j < cols_b; j++) { sum =0; sum =0; for (k=0; k < cols_a; k++) for (k=0; k < cols_a; k++) sum += (a[i][k] *b[k][j]); sum += (a[i][k] *b[k][j]); d[i][j] =sum; d[i][j] =sum; } }

O(rows_a * cols_a * cols_b) vs. O(rows_a * cols_a * cols_b) vs. O(cols_b * total_a + rows_a * total_b)O(cols_b * total_a + rows_a * total_b)

optimal case:optimal case:total_a < rows_a * cols_a total_b < cols_a * cols_btotal_a < rows_a * cols_a total_b < cols_a * cols_b

worse case:worse case:total_a --> rows_a * cols_a, or total_a --> rows_a * cols_a, or total_b --> cols_a * cols_btotal_b --> cols_a * cols_b

Page 42: Chapter 2 Arrays and Structures  The array as an abstract data type  Structures and Unions  The polynomial Abstract Data Type  The Sparse Matrix Abstract

2.5 Representation of 2.5 Representation of multidimensional array (1/5)multidimensional array (1/5)

The internal representation of multidimensional The internal representation of multidimensional arrays requires more complex addressing arrays requires more complex addressing formula.formula. If an array is declared If an array is declared aa[[upperupper00][][upperupper11]…[]…[upperuppernn], ],

then it is easy to see that the number of elements in then it is easy to see that the number of elements in the array is:the array is:

Where Where is the product of the is the product of the upperupperii’s.’s.

Example:Example: If we declare If we declare aa as as aa[10][10][10], then we require 10*10*10 = [10][10][10], then we require 10*10*10 =

1000 units of storage to hold the array.1000 units of storage to hold the array.

1

0

n

iiupper

Page 43: Chapter 2 Arrays and Structures  The array as an abstract data type  Structures and Unions  The polynomial Abstract Data Type  The Sparse Matrix Abstract

2.5 Representation of 2.5 Representation of multidimensional array (2/5)multidimensional array (2/5)

Represent multidimensional arrays: Represent multidimensional arrays: row majorrow major order order and and column majorcolumn major order order.. Row major order stores multidimensional arrays Row major order stores multidimensional arrays

by rows.by rows. A[A[upperupper00][][upperupper11] as ] as

upperupper00 rows, rows, rowrow00, , rowrow11, …, , …, rowrowupper0-1upper0-1, ,

each row containing each row containing upper1upper1 elements. elements.

Page 44: Chapter 2 Arrays and Structures  The array as an abstract data type  Structures and Unions  The polynomial Abstract Data Type  The Sparse Matrix Abstract

2.5 Representation of 2.5 Representation of multidimensional array (3/5)multidimensional array (3/5)

Row major order:A[i][j] : + i*upper1 + j

Column major order: A[i][j] : + j*upper0 + i

col0 col1 colu1-1

row0 A[0][0] A[0][1] . . . A[0][u1-1] + u0 +(u1-1)* u0

row1 A[1][0] A[1][1] . . . A[1][u1-1] + u1

. . .rowu0-1A[u0-1][0] A[u0-1][1] . . . A[u0-1][u1-1]

+(u0-1)*u1

Page 45: Chapter 2 Arrays and Structures  The array as an abstract data type  Structures and Unions  The polynomial Abstract Data Type  The Sparse Matrix Abstract

2.5 Representation of 2.5 Representation of multidimensional array (4/5)multidimensional array (4/5)

To represent a three-dimensional array, To represent a three-dimensional array, AA[[upperupper00]]

[[upperupper11][][upperupper22], we interpret the array as ], we interpret the array as upperupper00

two-dimensional arrays of dimension two-dimensional arrays of dimension upperupper11upperupper22.. To locate To locate aa[[ii][][jj][][kk], we first obtain ], we first obtain + + i*upperi*upper11

**upperupper22 as as

the address of the address of aa[[ii][0][0] because there are i two ][0][0] because there are i two dimensional arrays of size dimensional arrays of size upperupper11**upperupper22 preceding this preceding this

element.element. + + ii**upperupper11**upperupper22++j j **upperupper22++kk

as the address of as the address of aa[[ii][][jj][][kk].].

Page 46: Chapter 2 Arrays and Structures  The array as an abstract data type  Structures and Unions  The polynomial Abstract Data Type  The Sparse Matrix Abstract

2.5 Representation of 2.5 Representation of multidimensional array (5/5)multidimensional array (5/5)

Generalizing on the preceding discussion, we can Generalizing on the preceding discussion, we can obtain the addressing formula for any element obtain the addressing formula for any element AA[[ii00]]

[[ii11]…[]…[iin-1n-1] in an ] in an nn-dimensional array declared as: -dimensional array declared as:

AA[[upperupper00][][upperupper11]…[]…[upperuppern-1n-1] ] The address for A[i0][i1]…[in-1] is:

Page 47: Chapter 2 Arrays and Structures  The array as an abstract data type  Structures and Unions  The polynomial Abstract Data Type  The Sparse Matrix Abstract

2.6 The String Abstract data 2.6 The String Abstract data type(1/19)type(1/19)

2.6.1 Introduction2.6.1 Introduction The String: component elements are characters.The String: component elements are characters.

A string to have the form, S = s0, …, sn-1, where si

are characters taken from the character set of the

programming language.

If n = 0, then S is an empty or null string.

Operations in ADT 2.4, p. 81

Page 48: Chapter 2 Arrays and Structures  The array as an abstract data type  Structures and Unions  The polynomial Abstract Data Type  The Sparse Matrix Abstract

2.6 The String Abstract data 2.6 The String Abstract data type(2/19)type(2/19)

ADT ADT StringString::

Page 49: Chapter 2 Arrays and Structures  The array as an abstract data type  Structures and Unions  The polynomial Abstract Data Type  The Sparse Matrix Abstract

2.6 The String Abstract data 2.6 The String Abstract data type(3/19)type(3/19)

In C, we represent strings as character arrays In C, we represent strings as character arrays terminated with the null character \0.terminated with the null character \0.

Figure 2.8 shows how these strings would be Figure 2.8 shows how these strings would be represented internally in memory.represented internally in memory.

Page 50: Chapter 2 Arrays and Structures  The array as an abstract data type  Structures and Unions  The polynomial Abstract Data Type  The Sparse Matrix Abstract

2.6 The String Abstract data 2.6 The String Abstract data type(4/19)type(4/19)

Now suppose we want to concatenate these Now suppose we want to concatenate these strings together to produce the new string:strings together to produce the new string: Two strings are joined together by strcat(s, t), which stores the

result in s. Although s has increased in length by five, we have

no additional space in s to store the extra five characters. Our

compiler handled this problem inelegantly: it simply overwrote

the memory to fit in the extra five characters. Since we declared

t immediately after s, this meant that part of the word “house”

disappeared.

Page 51: Chapter 2 Arrays and Structures  The array as an abstract data type  Structures and Unions  The polynomial Abstract Data Type  The Sparse Matrix Abstract

2.6 The String Abstract data 2.6 The String Abstract data type(5/19)type(5/19)

C string C string

functionsfunctions

Page 52: Chapter 2 Arrays and Structures  The array as an abstract data type  Structures and Unions  The polynomial Abstract Data Type  The Sparse Matrix Abstract

2.6 The String Abstract data 2.6 The String Abstract data type(6/19)type(6/19)

Example 2.2[String insertion]:Example 2.2[String insertion]: Assume that we have two strings, say Assume that we have two strings, say stringstring 1 and 1 and

stringstring 2, and that we want to insert 2, and that we want to insert stringstring 2 into 2 into stringstring 1 starting at the 1 starting at the ii th position of th position of stringstring 1. We begin with 1. We begin with the declarations: the declarations:

In addition to creating the two strings, we also have In addition to creating the two strings, we also have created a pointer for each string.created a pointer for each string.

Page 53: Chapter 2 Arrays and Structures  The array as an abstract data type  Structures and Unions  The polynomial Abstract Data Type  The Sparse Matrix Abstract

2.6 The String Abstract data 2.6 The String Abstract data type(7/19)type(7/19)

Now suppose that the first string contains Now suppose that the first string contains “amobile” and the second contains “uto”.“amobile” and the second contains “uto”. we want to insert “uto”we want to insert “uto”

starting at position 1 ofstarting at position 1 of

the first string, thereby the first string, thereby

producing the wordproducing the word

“ “automobile.’automobile.’

Page 54: Chapter 2 Arrays and Structures  The array as an abstract data type  Structures and Unions  The polynomial Abstract Data Type  The Sparse Matrix Abstract

2.6 The String Abstract data 2.6 The String Abstract data type(8/19)type(8/19)

String insertion function:String insertion function: It should never be used in practice as it is wasteful in It should never be used in practice as it is wasteful in

its use of time and space.its use of time and space.

Page 55: Chapter 2 Arrays and Structures  The array as an abstract data type  Structures and Unions  The polynomial Abstract Data Type  The Sparse Matrix Abstract

2.6 The String Abstract data 2.6 The String Abstract data type(9/19)type(9/19)

2.6.2 Pattern Matching:2.6.2 Pattern Matching: Assume that we have two strings, Assume that we have two strings, stringstring and and pat pat where where patpat is a is a

pattern to be searched for in pattern to be searched for in stringstring. . If we have the following declarations:If we have the following declarations:

Then we use the following statements to determine if Then we use the following statements to determine if patpat is in is in stringstring::

If If patpat is not in is not in stringstring, this method has a computing time of , this method has a computing time of O(O(n*mn*m) where ) where nn is the length of is the length of patpat and and m m is the length of is the length of stringstring..

Page 56: Chapter 2 Arrays and Structures  The array as an abstract data type  Structures and Unions  The polynomial Abstract Data Type  The Sparse Matrix Abstract

2.6 The String Abstract data 2.6 The String Abstract data type(10/19)type(10/19)

We can improve on an exhaustive pattern We can improve on an exhaustive pattern matching technique by quitting when matching technique by quitting when strlenstrlen((patpat) ) is greater than the number of remaining is greater than the number of remaining characters in the string.characters in the string.

Page 57: Chapter 2 Arrays and Structures  The array as an abstract data type  Structures and Unions  The polynomial Abstract Data Type  The Sparse Matrix Abstract

2.6 The String Abstract data 2.6 The String Abstract data type(11/19)type(11/19)

Example 2.3 [Simulation of Example 2.3 [Simulation of nfindnfind]] Suppose Suppose patpat=“aab” =“aab”

and and

stringstring=“ababbaabaa.”=“ababbaabaa.” Analysis of Analysis of nfindnfind::

The computing time for The computing time for

these string is linearthese string is linear

in the length of the in the length of the

string O(string O(mm), but the ), but the

Worst case is still Worst case is still

O(O(n.mn.m).).

Page 58: Chapter 2 Arrays and Structures  The array as an abstract data type  Structures and Unions  The polynomial Abstract Data Type  The Sparse Matrix Abstract

2.6 The String Abstract data 2.6 The String Abstract data type(12/19)type(12/19)

Ideally, we would like an algorithm that works in Ideally, we would like an algorithm that works in

O(O(strlenstrlen((stringstring)+)+strlenstrlen((patpat)) time.This is optimal )) time.This is optimal for this problem as in the worst case it is for this problem as in the worst case it is necessary to look at all characters in the pattern necessary to look at all characters in the pattern and string at least once.and string at least once.

Knuth,Morris, and Pratt have developed a Knuth,Morris, and Pratt have developed a pattern matching algorithm that works in this way pattern matching algorithm that works in this way and has linear complexity.and has linear complexity.

Page 59: Chapter 2 Arrays and Structures  The array as an abstract data type  Structures and Unions  The polynomial Abstract Data Type  The Sparse Matrix Abstract

2.6 The String Abstract data 2.6 The String Abstract data type(13/19)type(13/19)

Suppose pat = “a b c a b c a c a b”Suppose pat = “a b c a b c a c a b”

Page 60: Chapter 2 Arrays and Structures  The array as an abstract data type  Structures and Unions  The polynomial Abstract Data Type  The Sparse Matrix Abstract

2.6 The String Abstract data 2.6 The String Abstract data type(14/19)type(14/19)

From the definition of the failure function, we arrive at From the definition of the failure function, we arrive at the following rule for pattern matching: if a partial the following rule for pattern matching: if a partial match is found such that match is found such that Si-j…Si-1=P0P1…Pj-1 Si-j…Si-1=P0P1…Pj-1 and and SSi i !=!= Pj then matching may be resumed by comparing Pj then matching may be resumed by comparing Si and Pf(j-1)+1 if j Si and Pf(j-1)+1 if j != != 0 .If j= 0, then we may continue 0 .If j= 0, then we may continue by comparing Si+1 and P0.by comparing Si+1 and P0.

Page 61: Chapter 2 Arrays and Structures  The array as an abstract data type  Structures and Unions  The polynomial Abstract Data Type  The Sparse Matrix Abstract

2.6 The String Abstract data 2.6 The String Abstract data type(15/19)type(15/19)

This pattern matching rule translates into This pattern matching rule translates into function function pmatchpmatch..

Page 62: Chapter 2 Arrays and Structures  The array as an abstract data type  Structures and Unions  The polynomial Abstract Data Type  The Sparse Matrix Abstract

2.6 The String Abstract data 2.6 The String Abstract data type(16/19)type(16/19)

Analysis of Analysis of pmatchpmatch:: The The whilewhile loop is iterated until the end of either the string or loop is iterated until the end of either the string or

the pattern is reached. Since the pattern is reached. Since i i is never decreased, the lines is never decreased, the lines that increase that increase i i cannot be executed more than cannot be executed more than mm = = strlen(string) strlen(string) times. The resetting of times. The resetting of jj to to failurefailure[j-1]+1 [j-1]+1 decreases decreases j++j++ as otherwise, as otherwise, j j falls off the pattern. Each time falls off the pattern. Each time the statement the statement j++j++ is executed, is executed, i i is also incremented. So is also incremented. So j j cannot be incremented more than m times. Hence the cannot be incremented more than m times. Hence the complexity of function complexity of function pmatchpmatch is O( is O(mm) = O() = O(strlenstrlen((stringstring)).)).

Page 63: Chapter 2 Arrays and Structures  The array as an abstract data type  Structures and Unions  The polynomial Abstract Data Type  The Sparse Matrix Abstract

2.6 The String Abstract data 2.6 The String Abstract data type(17/19)type(17/19)

If we can compute the failure function in O(If we can compute the failure function in O(strlenstrlen((patpat)) )) time, then the entire pattern matching process will time, then the entire pattern matching process will have a computing time proportional to the sum of the have a computing time proportional to the sum of the lengths of the string and pattern. Fortunately, there is lengths of the string and pattern. Fortunately, there is a fast way to compute the failure function. This is a fast way to compute the failure function. This is based upon the following restatement of the failure based upon the following restatement of the failure function:function:

Page 64: Chapter 2 Arrays and Structures  The array as an abstract data type  Structures and Unions  The polynomial Abstract Data Type  The Sparse Matrix Abstract

2.6 The String Abstract data 2.6 The String Abstract data type(18/19)type(18/19)

Page 65: Chapter 2 Arrays and Structures  The array as an abstract data type  Structures and Unions  The polynomial Abstract Data Type  The Sparse Matrix Abstract

2.6 The String Abstract data 2.6 The String Abstract data type(19/19)type(19/19)

Analysis of Analysis of failfail:: In each iteration of the In each iteration of the while while loop the value of loop the value of i i

decreases (by the definition ofdecreases (by the definition of f f ). The variable ). The variable i i is reset is reset at the beginning of each iteration of the at the beginning of each iteration of the forfor loop. loop. However, it is either reset to -1(initially or when the However, it is either reset to -1(initially or when the previous iteration of the previous iteration of the forfor loop goes through the last loop goes through the last elseelse clause) or it is reset to a value 1 greater than its clause) or it is reset to a value 1 greater than its terminal value on the previous iteration (i.e., when the terminal value on the previous iteration (i.e., when the statement statement failurefailure [ [ j j ] =] = i i+1 is executed). Since the +1 is executed). Since the forfor loop is iterated only loop is iterated only nn-1(-1(nn is the length of the pattern) is the length of the pattern) times, the value of times, the value of ii has a total increment of at most has a total increment of at most nn-1. -1. Hence it cannot be decremented more thanHence it cannot be decremented more than n n-1 times.-1 times.

Consequently the Consequently the whilewhile loop is iterated at most loop is iterated at most nn-1 times -1 times over the whole algorithm and the computing time of fail is over the whole algorithm and the computing time of fail is O(O(nn) = O() = O(strlenstrlen((patpat)).)).