Presentation is loading. Please wait.

Presentation is loading. Please wait.

CH2. ARRAYS.

Similar presentations


Presentation on theme: "CH2. ARRAYS."— Presentation transcript:

1 CH2. ARRAYS

2 2.1 Abstract Data Types and the C++ Class
2.1.1 C++ Class : represents an ADT Consists of four components class name data members member functions levels of program access public : anywhere private : within its (friend) class a function protected : within its class friend 9/22/2018

3 2.1 Abstract Data Types and the C++ Class(Cont’)
#ifndef RECTANGLE_H #define RECTANGLE_H    // In the header file Rectangle.h class Rectangle {        public:             // the following members are public   // The next four members are member functions         Rectangle();       // constructor         ~Rectangle();      // destructor         int GetHeight();  // returns the height of the rectangle         int GetWidth();   // returns the width of the rectangle private:    // the following members are private   // the following members are data members         int x1, y1, h, w;         // (x1, y1) are the coordinates of the bottom left corner of the rectangle         // w is the width of the rectangle; h is the height of the rectangle }; #endif Program 2.1 : Definition of the C++ class Rectangle 9/22/2018

4 2.1 Abstract Data Types and the C++ Class(Cont’)
2.1.2 Data Abstraction and Encapsulation in C++ Data encapsulation of C++ class all data members are private (or protected) external access to data members are by member functions Separation of specification and implementation of member functions specification (function prototype) name of functions type of function arguments type of function result Implementation placed in a source file of the same name can be included inside its class definition 9/22/2018

5 2.1 Abstract Data Types and the C++ Class(Cont’)
// In the source file Rectangle.C #include "Rectangle.h" // The prefix “Rectangle::" identifies GetHeight() and // GetWidth() as member functions // belonging to class Rectangle. It is required because the member functions // are implemented outside their class definition int Rectangle::GetHeight() {return h;} int Rectangle::GetWidth() {return w;} Program 2.2 : Implementation of operations on Rectangle 9/22/2018

6 2.1 Abstract Data Types and the C++ Class(Cont’)
2.1.3 Declaring class objects in the same way as variables Invoking member functions using component selection operators dot(.) : direct selection arrow : indirect selection through a pointer 9/22/2018

7 2.1 Abstract Data Types and the C++ Class(Cont’)
// In a source file main.C #include <iostream.h> #include "Rectangle.h" main() {         Rectangle r, s;   // r and s are objects of class Rectangle         Rectangle *t = &s;   // t is a pointer to class object s         ….. // use . to access members of class objects. // use → to access members of class objects through pointers.         if (r.GetHeight()*r.GetWidth() >t→GetHeight() * t→GetWidth())          cout << " r ";         else cout << " s ";         cout << "has the greater area" << endl; } Program 2.3 : A C++ code fragment demonstrating how Rectangle objects are declared and member functions invoked 9/22/2018

8 2.1 Abstract Data Types and the C++ Class(Cont’)
2.1.4 Special Class Operations Constructor a member function which initializes data members of an object If provided for a class, automatically executed when an object of that class is created must be public the name must be identical to the name of the class must not specify a return type or return a value Rectangle::Rectangle(int x, int y, int height, int width) {         x1=x; y1=y;         h=height; w=width; } Program 2.4 : Definition of a constructor for Rectangle 9/22/2018

9 2.1 Abstract Data Types and the C++ Class(Cont’)
initialize Rectangle object using constructor Rectangle r(1, 3, 6, 6); Rectangle *s = new Rectangle(0, 0, 3, 4); initialize using a default constructor Rectangle r; Rectangle::Rectangle (int x=0, int y=0,                          int height=0, int width=0) : x1 (x), y1(y), h(height), w(width) { } Program 2.5 : A default constructor 9/22/2018

10 2.1 Abstract Data Types and the C++ Class(Cont’)
Destructor a member function which deletes data members automatically invoked when a class object goes out of scope or is deleted must be public its class name prefixed with ~ if a data member is a pointer, only the space of the pointer is returned Operator overloading polymorphism : same operator for different situations for example, algorithm comparing two floats is different from algorithm comparing two ints 9/22/2018

11 2.1 Abstract Data Types and the C++ Class(Cont’)
int Rectangle::operator==(const Rectangle &s ) {         if (this == &s) return 1;         if ((x1 == s.x1) && (y1 == s.y1) && (h == s.h) && (w == s.w)) return 1;         else return 0; } Program 2.6 : Overloading operator == for class Rectangle 9/22/2018

12 2.1 Abstract Data Types and the C++ Class(Cont’)
this represents a pointer to the object that invoked a member function *this represents the object 9/22/2018

13 2.1 Abstract Data Types and the C++ Class(Cont’)
Ostream& operator<<(ostream& os, Rectangle& r) { os << “Position is : ” << r.xl << “ ”; os << r.yl << endl; os << “Height is : ” << r.h << endl; os << “Width is : ” << r.w << endl; return os; } Program 2.7 : Overloading operator << for class Rectangle 9/22/2018

14 2.1 Abstract Data Types and the C++ Class(Cont’)
2.1.5 Miscellaneous Topics static class data member a global variable for its class there is only one copy of a static data member and all class objects share it declaration does not constitute a definition 9/22/2018

15 2.1 Abstract Data Types and the C++ Class(Cont’)
2.1.6 ADTs and C++ classes They are similar Some operators in C++, when overloaded for user defined ADTs, are declared outside the C++ class definition of the ADT 9/22/2018

16 2.1 Abstract Data Types and the C++ Class(Cont’)
class NaturalNumber{ // An ordered subrange of the integers starting at zero and ending at // the maximum integer (MAXINT) on the computer public:         NaturalNumber Zero();         // returns 0         Boolean IsZero();         // if *this is 0, return TRUE; otherwise, return FALSE         NaturalNumber Add(NaturalNumber y);         // return the smaller of *this+y and MAXINT;         Boolean Equal(NaturalNumber y);         // return TRUE if *this==y; otherwise return FALSE         NaturalNumber Successor();         // if *this is MAXINT return MAXINT; otherwise return *this+1         NaturalNumber Substract(NaturalNumber y);         // if *this<y, return 0; otherwise return *this-y }; ADT 1.2 : Abstract data type NaturalNumber 9/22/2018

17 2.2 Array As Abstract Data Type
a set of pairs <index, value> ADT for array provides operations retrieves a value stores a value C++ Array index starts at 0 C++ does not check bounds for an array index example float example[n]; ith element: example[i] and *(example+i) 9/22/2018

18 2.2 Array As Abstract Data Type(Cont’)
Class GeneralArray { // objects: A set of pairs <index, value> where for each value of index // in IndexSet there is a value of type float. // IndexSet is a finite ordered set of one or more dimensions, // for example, {0, ..., n-1} for one dimension, // {(0,0), (0,1), (0,2), (1,0), (1,1), (1,2), (2,0), (2,1), (2,2)} for two // dimensions, etc. public:       GeneralArray(int j, RangeList list, float initValue = defaultValue);       // The constructor GeneralArray creates a j dimensional array       // of floats; the range of the kth dimension is given by the       // kth element of list. For each index i in the index set, insert       // <i, initValue> into the array.       9/22/2018

19 2.2 Array As Abstract Data Type(Cont’)
float Retrieve(index i);       // if (i is in the index set of the array) return the float       // associated with i in the array; else signal an error.       void Store(index i, float x);       // if (i  is in the index set of the array) delete any pair of the       // form <i, y> present in the array and insert the new pair         // <i, x>; else signal an error. }; // end of GeneralArray ADT 2.1 : Abstract data type GeneralArray 9/22/2018

20 2.3 Polynomial Abstract Data Type
Ordered (or linear) list days of the week : (Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday) years Switzerland fought in WWII : () Operations on lists (a0, a1, ..., an-1) : find the length, n, of the list read the list from left to right (or reverse) retrieve the ith element, 0≤i<n store a new value into the ith position, 0≤i<n insert a new element at the position i, 0≤i<n delete the element at position i, 0≤i<n 9/22/2018

21 2.3 Polynomial Abstract Data Type(Cont’)
requires ordered lists the largest exponent is called degree sum and product of polynomials A(x) = ∑aixi  and  B(x) = ∑bixi A(x) + B(x) = ∑(ai + bi)xi A(x) ‧ B(x) = ∑(aixi ․∑(bjxj)) 9/22/2018

22 2.3 Polynomial Abstract Data Type(Cont’)
Class Polynomial {      // objects : p(x) = a0xe0 + … + anxe0 ; a set of ordered pairs of <ei, ai>, // where ai ∈ Coefficient and ei ∈ Exponent      // We assume that Exponent consists of integers ≥ 0    public:       Polynomial();       // return the polynomial p(x)=0 int operator!();       // If *this is the zero polynomial, return 1; else return 0;       Coefficient Coef(Exponent e);       // return the coefficient of e in *this       Exponent LeadExp();       // return the largest exponent in *this       9/22/2018

23 2.3 Polynomial Abstract Data Type(Cont’)
Polynomial Add(Polynomial poly);      // return the sum of the polynomials *this and poly       Polynomial Mult(Polynomial poly);      // return the product of the polynomials *this and poly       float Eval(float f);       // Evaluate the polynomial *this at f and return the result.   }; // end of polynomial ADT 2.2 : Abstract data type Polynomial 9/22/2018

24 2.3 Polynomial Abstract Data Type(Cont’)
2.3.1 Polynomial Representation Principle unique exponents are arranged in decreasing order 9/22/2018

25 2.3 Polynomial Abstract Data Type(Cont’)
Representation 1 (Array: static memory allocation) define the private data members of Polynomial private : int degree ; // degree≤MaxDegree float coef[MaxDegree+1] ; for Polynomial object a, n≤MaxDegree a.degree=n a.coef[i]=an-i, 0≤i≤n a.coef[i] is the coefficient of xn-I A(x)=anxn+an-1xn-i+...+a1x+a0 leads to a very simple algorithms for many of the operations on polynomials wastes computer memory for example, if a.degree MaxDegree 9/22/2018

26 2.3 Polynomial Abstract Data Type(Cont’)
Representation 2 (Array: dynamic memory allocation) define coef with size a.degree+1 declare private data members private : int degree ; float *coef ; add a constructor to Polynomial Polynomial::Polynomial(int d) { degree=d ; coef=new float[degree+1] ; } wastes space for sparse polynomials for example, x1000+1 9/22/2018

27 2.3 Polynomial Abstract Data Type(Cont’)
Representation 3 previously, exponents are represented by array indices now, (non-zero) exponents are stored all Polynomials will be represented in a single array called termArray termArray is shared by all Polynomial objects it is declared as static each element in termArray is of type term class term { friend Polynomial ; private : float coef ; // coefficient int exp ; // exponent }; 9/22/2018

28 2.3 Polynomial Abstract Data Type(Cont’)
declare private data members of Polynomial class Polynomial { private : static term termArray[MaxTerms]; static int free; int Start, Finish; public: Polynomial ADD(Polynomial poly); ... } required definitions of the static class members outside the class definition term Polynomial::termArray[MaxTerms]; int Polynomial::free=0; // next free location in termArray A(x)=2x1000+1, B(x)=x4+10x3+3x2+1 9/22/2018

29 2.3 Polynomial Abstract Data Type(Cont’)
A.Start A.Finish B.Start B.Finish Free coef 2 1 1 10 3 1 exp 1000 4 3 2 1 2 3 4 5 6 Figure 2.1 : Array representation of two polynomials 9/22/2018

30 2.3 Polynomial Abstract Data Type(Cont’)
A(x) has n nonzero terms A.Finish=A.Start+n-1 if n=0, A.Finish=A.Start-1 comparison with Representation 2 Representation 3 is superior when many zero terms are present as in A(x) when all terms are nonzero, as in B(x), Representation 3 uses about twice as much space as Representation 2 9/22/2018

31 2.3 Polynomial Abstract Data Type(Cont’)
2.3.2 Polynomial Addition Representation 3 is used C(x)=A(x)+B(x) 9/22/2018

32 2.3 Polynomial Abstract Data Type(Cont’)
Polynomial Polynomial::Add(Polynomial B) // return the sum of A(x) (in *this) and B(x) { Polynomial C; int a = Start; int b = B.Start; C.Start = free; float c; while ((a<=Finish) && (b<=B.Finish) switch (compare(termArray[a].exp, termArray[b].exp)){ case '=': c = termArray[a].coef + termArray[b].coef; if (c) NewTerm(c, termArray[a].exp); a++; b++; break; case '<': NewTerm(termArray[b].coef, termArray[b].exp); b++; 9/22/2018

33 2.3 Polynomial Abstract Data Type(Cont’)
case '>': NewTerm(termArray[a].coef, termArray[a].exp); a++; }// end of switch and while // add in remaining terms of A(x) for (; a<=Finish; a++) // add in remaining terms of B(x) for (; b<=B.Finish; b++) Newterm(termArray[b].coef, termArray[b].exp); C.Finish = free - 1; return C; } // end of Add Program 2.8 : Adding two polynomials 9/22/2018

34 2.3 Polynomial Abstract Data Type(Cont’)
void Polynomial::NewTerm(float c, int e) // Add a new term to C(x). { if (free>=MaxTerms) { cerr << "Too many terms in polynomials" << endl; exit(1); } termArray[free].coef = c; termArray[free].exp = e; free++; }// end of NewTerm Program 2.9 : Adding a new term 9/22/2018

35 2.3 Polynomial Abstract Data Type(Cont’)
Analysis of Add m and n are number of nonzero-terms in A and B, respectively the while loop of line 5 is bounded by m+n-1 the for loops of lines 21 and 24 are bounded by O(n+m) summing up, the asymptotic computing time is O(n+m) Disadvantages of representing polynomials by arrays space must be reused for unused polynomials linked lists in chapter 4 provide a solution 9/22/2018

36 2.4 Sparse Matrices 2.4.1 Introduction
Matrix with m rows and n columns m×n (m by n) mn elements when m=n, the matrix is square Storing a matrix two dimensional array A[m][n] an element is A[i][j] sparse matrix store only the nonzero elements 9/22/2018

37 2.4 Sparse Matrices(Cont’)
Matrix operations Creation Transposition Addition multiplication -27 3 4 6 82 -2 109 -64 11 12 8 9 15 -15 -6 91 28 48 27 47 1 2 5 (a) (b) Figure 2.2 : Two matrices 9/22/2018

38 2.4 Sparse Matrices(Cont’)
Class SparseMatrix { // objects : A set of triples, <row, column, value>, where row // and column are integers and form a unique combination; value // is also an integer. public: SparseMatrix(int MaxRow, int MaxCol); // the constructor function creates a SparseMatrix // that can hold up to MaxItems=MaxRow x MaxCol and whose // maximum row size is MaxRow and whose maximum // column size is MaxCol SparseMatrix Transpose(); // returns the SparseMatrix obtained by interchanging the // row and column value of every triple in *this 9/22/2018

39 2.4 Sparse Matrices(Cont’)
SparseMatrix Add(SparseMatrix b); // if the dimensions of a(*this) and b are the same, then // the matrix produced by adding corresponding items, // namely those with identical row and column values is // returned else error. SparseMatrix Multiply(SparseMatrix b); // if number of columns in a (*this) equals number of // rows in b then the matrix d produced by multiplying a // by b according to the formula // d[i][j]= (a[i][k]·b[k][j]), // where d[i][j] is the (i, j)th element, is returned. // k ranges from 0 to the number of columns in a-1 // else error. }; ADT 2.3 : Abstract data type SparseMatrix 9/22/2018

40 2.4 Sparse Matrices(Cont’)
2.4.2 Sparse Matrix Representation Representation use the triple <row, col, value> to represent an element store the triples by rows for each row, the column indices are in ascending order store the number of rows, columns, and nonzero elements 9/22/2018

41 2.4 Sparse Matrices(Cont’)
C++ code class SparseMatrix; // forward declaration class MatrixTerm { friend class SparseMatrix private: int row, col, value; }; class SparseMatrix { int Rows, Cols, Terms; MatrixTerm smArray[MaxTerms]; public: SparseMatrix Transpose(); ... } 9/22/2018

42 2.4 Sparse Matrices(Cont’)
Representation of the matrix of Figure 2.2(b) using smArray row col value row col value smArray[0] 15 smArray[0] 15 [1] 3 22 [1] 4 91 [2] 5 -15 [2] 1 1 11 [3] 1 1 11 [3] 2 1 3 [4] 1 2 3 [4] 2 5 28 [5] 2 3 -6 [5] 3 22 [6] 4 91 [6] 3 2 -6 [7] 5 2 28 [7] 5 -15 (b) Figure 2.3 : Sparse matrix and its transpose stored as triples 9/22/2018

43 2.4 Sparse Matrices(Cont’)
2.4.3 Transposing a Matrix n element at [i][j] will be at [j][i] for (each row i) take element (i, j, value) and store it in (j, i, value) of the transpose; Example (0, 0, 15) → (0, 0, 15) (0, 3, 22) → (3, 0, 22) (0, 5, -15) → (5, 0, -15) (1, 1, 11) → (1, 1, 11) need to insert many new triples, elements are moved down very often Find the elements in the order for (all elements in column j) place element (i, j, value) in position (j, i, value); 9/22/2018

44 2.4 Sparse Matrices(Cont’)
SparseMatrix SparseMatrix::Transpose() // return the transpose of a (*this) { SparseMatrix b; b.Rows = Cols; // rows in b = columns in a b.Cols = Rows; // columns in b = rows in a b.Terms = Terms; // terms in b = terms in a if (Terms > 0) // nonzero matrix int CurrentB = 0; for (int c = 0; c < Cols; c++) // transpose by columns for (int i = 0; i < Terms; i++) // find elements in column c 9/22/2018

45 2.4 Sparse Matrices(Cont’)
if (smArray[i].col ==c) { b.smArray[CurrentB].row = c; b.smArray[CurrentB].col = smArray[i].row; b.smArray[CurrentB].value = smArray[i].value; CurrentB++; } } // end of if (Terms > 0) return b; } // end of transpose Program 2.10 : Transposing a matrix 9/22/2018

46 2.4 Sparse Matrices(Cont’)
Analysis of transpose the number of iterations of the for loop at line 12 is terms the number of iterations of the for loop at line 11 is columns total time is O(terms·columns) total space is O(space for a and b) Using two-dimensional arrays for(int j=0; j<columns; j++) for(int i=0; i<rows; i++) B[j][i]=A[i][j]; total time is O(rows·columns) 9/22/2018

47 2.4 Sparse Matrices(Cont’)
Comparison O(terms·columns) =O(rows·columns2) > O(rows·columns) space-time trade-off 9/22/2018

48 2.4 Sparse Matrices(Cont’)
FastTranspose algorithm determine the number of elements in each column of a → the number of elements in each row of b → starting point of each of b's rows move elements of a one by one into their correct position in b values for Figure 2.3 (b) matrix [0] [1] [2] [3] [4] [5] RowSize = 2 1 2 2 1 RowStart = 2 3 5 7 7 9/22/2018

49 2.4 Sparse Matrices(Cont’)
asymptotic complexity there are four loops O(columns+terms) if terms → rows·columns, O(rows·columns) if terms << rows·columns, less than requires space for RowSize and RowStart 9/22/2018

50 2.4 Sparse Matrices(Cont’)
SparseMatrix SparseMatrix::FastTranspose() // The transpose of a (*this) is placed in b and is found in // O(terms+columns) time. { int *RowSize = new int[Cols]; int *RowStart = new int[Cols]; SparseMatrix b; b.Rows = Cols; b.Cols = Rows; b.Terms = Terms; if (Terms>0) // nonzero matrix // compute RowSize[i] = number of terms in row i of b for (int i = 0; i<Cols; i++) RowSize[i] = 0; // initialize for (i = 0; i<Terms; i++) RowSize[smArray[i].col]++; // RowStart[i] = starting position of row i in b RowStart[0] = 0; 9/22/2018

51 2.4 Sparse Matrices(Cont’)
for (i =1; i<Cols; i++) RowStart[i] = RowStart[i-1] + RowSize[i-1]; for (i = 0; i<Terms; i++) // move from a to b { int j = RowStart[smArray[i].col]; b.smArray[j].row = smArray[i].col; b.smArray[j].col = smArray[i].row; b.smArray[j].value = smArray[i].value; RowStart[smArray[i].col]++; } // end of for } // end of if delete [] RowSize; delete [] RowStart; return b; } // end of FastTranspose Program 2.11 : Transposing a matrix faster 9/22/2018

52 2.4 Sparse Matrices(Cont’)
2.4.4 Matrix Multiplication A : m x n B : n x p By using sparse matrix Pick a row of A and find all elements in column j of B for j = 0, 1, .., B.col-1 , where B.col is the number of columns in B By using the transpose of B We can avoid the scanning all of B to find all the elements in column j All column elements are in consecutive order in B We just do a simple merge operation for the multiplication 9/22/2018

53 2.4 Sparse Matrices(Cont’)
= Figure 2.4 : Multiplication of two sparse matrices 9/22/2018

54 2.5 Representation of Multidimensional Arrays
A[p1 ... q1] [p2 ... q2], …., [pn ... qn], Where pi ... qi is the range of index values in dimension i the number of elements : an element A[i1][i2] ... [in] is mapped onto a position in a one-dim C++ array Row major order example A[4..5][2..4][1..2][3..4] 2*3*2*2 = 24 elements stored as A[4][2][1][3], A[4][2][1][4], ..., A[5][4][2][3], A[5][4][2][4] indices are increasing : lexicographic order translate to locations in the one-dim array A[4][2][1][3] → position 0 A[4][2][1][4] → position 1 A[5][4][2][4] → position 23 9/22/2018

55 2.5 Representation of Multidimensional Arrays(Cont’)
Translation for an n-dim array assume pi=0 and qi=ui-1 one-dim array A[u1] two-dim array A[u1][u2] let α be the address of A[0][0] A[i][0] : α+i*u2 A[i][j] : α+i*u2+j array element: A[0] A[1] A[2] A[i] A[u1 - 1] address: +1 +2 +i +u1 - 1 Figure 2.5 : Sequential representation of A[u1] 9/22/2018

56 2.5 Representation of Multidimensional Arrays(Cont’)
col 0 col 1 col u2-1 row 0 X X X row 1 X X X row 2 X X X . . . row u1-1 X X X (a) u2 element u1 element row 0 row 1 row i row ui -1 i*u2 elements (b) Figure 2.6 : Sequential representation of A[u1][u2] 9/22/2018

57 2.5 Representation of Multidimensional Arrays(Cont’)
three-dim array A[u1][u2][u3] the address of A[0][0][0] : α A[i][0][0] : α + iu2u3 A[i][j][k] : α + iu2u3 + ju3 + k 9/22/2018

58 2.5 Representation of Multidimensional Arrays(Cont’)
3-dimensional array A[u1][u2][u3] regarded as u1 2-dimensional array A(0, u2, u3) A(1, u2, u3) A(i, u2, u3) A(u1-1, u2, u3) (b) Sequential row major representation of a 3-dimensional array. Each 2-dimensional array is represented as in Figure 2.6 Figure 2.7 : Sequential representation of A[u1][u2][u3] 9/22/2018

59 2.5 Representation of Multidimensional Arrays(Cont’)
n-dim array A[u1][u2] ... [un] the address of A[0][0] ... [0] :  A[i1][0], …, [0] : α+i1u2u3…un A[i1][i2][0], …,[0] : α+i1u2u3…un + i2u3u4…un A[i1] [i2] , ...,[in] :  +i1u2u3…un + i2u3u4…un + i3u4u5…un …. + in-1un + in = 9/22/2018

60 2.6 String Abstract Data Type
String ADT S=s0, ..., sn-1 where si are characters and n is the length of the string if n=0, S is an empty or null string operations for strings C++ string string literal constants (e.g., "abc") array of chars : string characters + null character assigned to variables of type char* (e.g., char* str="abc";) ith character of str : str[i] 9/22/2018

61 2.6 String Abstract Data Type(Cont’)
class String { // objects : A finite ordered set of zero or more characters. public: String(char *init, int m); // Constructor that initializes *this to string init of length m int operator==(String t); // if (the string represented by *this equals t) // return 1 (TRUE) // else return 0 (FALSE) int operator!(); // if *this is empty then return 1 (TRUE); int Length(); // return the number of characters in *this 9/22/2018

62 2.6 String Abstract Data Type(Cont’)
String Concat(String t); // return a string whose element are those *this followed by those of t. String Substr(int i, int j); // return a string containing j characters of *this at positions // i, i+1, ..., i+j-1 if these are valid positions of *this; // otherwise, return the empty string. int Find (String pat); // return an index i such that pat matches the substring of // *this that begins at position i. // Return -1 if pat is either empty or not a substring of *this } ADT 2.4 : Abstract data type String 9/22/2018

63 2.6 String Abstract Data Type(Cont’)
2.6.1 String Pattern Matching Function Find two strings s and pat : pat is searched for in s invocation : s.Find(pat) returns i : pat matches s beginning at position I returns -1 : pat is empty or is not a substring of s Implementation representation of strings Private char* str sequentially consider each position of s positions to the right of position LengthS-LengthP need not be considered 9/22/2018

64 2.6 String Abstract Data Type(Cont’)
int String::Find(String pat) // i is set to -1 if pat does not occur in s (*this): // otherwise i is set to point to the first position in *this, where pat begins. { char *p = pat.str, *s = str; int i=0; // i is starting point if (*p && *s) while (i<=Length() - pat.Length()) if (*p++ == *s++){ // characters match. get next char in pat and s if (!*p) return i; // match found } else { // no match i++; s = str + i; p = pat.str; return -1; // pat is empty or does not occur in s } // end of Find Program 2.14 : Exhaustive pattern matching 9/22/2018

65 2.6 String Abstract Data Type(Cont’)
the complexity is O(LengthP·LengthS) the number of execution of while loop to check *p==*s  LengthP the number of execution of while loop by incrementing i < LengthS 9/22/2018

66 2.6 String Abstract Data Type(Cont’)
2.6.2 String Pattern Matching: The Knuth-Morris-Pratt Algorithm (example) pat = ‘a b c a b c a c a b’ s = s0 s1 ... si ... sm-1 Determine a matching beginning at si If si != a, then compare si+1 and a If si == a, then compare si+1 and b If si+1 != b, then compare si+1 and a If sisi+1 == ab, then compare si+2 and c 9/22/2018

67 2.6 String Abstract Data Type(Cont’)
Situation(1) No need to compare the first (a) in pat with si+1, Since si+1 == the second (b) s = ‘- a b ? . ?’ part = ‘a c b’ 9/22/2018

68 2.6 String Abstract Data Type(Cont’)
Situation(2) : the first four characters matched, but si+4 != b Compare si+4 and the second (b): partial match by sliding pat. We can determine where to continue the search without moving backwards s = ‘- a b c ? . ?’ part = ‘a b’ 9/22/2018

69 2.6 String Abstract Data Type(Cont’)
Definition If p=p0p2…pn-1 is a pattern, then its failure function f, is defined as largest k<j such that p0p1…pk = pj-kpj-k+1…pj if such a k0 exists otherwise For the example pattern above Pat=abcabcacab, we have if a partial match is found such that si-j … si-1 = p0p1…pj-1 and sipj Matching may be resumed by comparing si and pf(j-1)+1 if j 0 If j=0 then we may continue by comparing si+1 and p0 This pattern-matching rule translates to function FastFind f(j)= pat a b c f -1 1 2 3 j 4 5 6 7 8 9 9/22/2018

70 2.6 String Abstract Data Type(Cont’)
int String::FastFind(String pat) { //Determine if pat is a substring of s int PostP=0, PosS=0; int LengthP=pat.Length(), LengthS=Length(); while ((PosP<LengthP) && (PosS<LengthS0)) if(pat.str[PosP]==str[PosS]){ //character match PosP++; PosS++; } else if(PosP==0) PosS++; else PosP=pat.f[PosP-1]+1; if(PosP<LengthP) return –1; else return PosS-LengthP; } //end of FastFind Analysis : O(LengthS) Program 2.15 pattern-matching with a failure function 9/22/2018

71 2.6 String Abstract Data Type(Cont’)
Failure function if j=0 f(j) = fm(j-1)+1 where m is the least integer k for which pfk(j-1)+1 = pj if there is no k satisfying the above (Note that f1(j) = f(j) and fm(j) = f(fm-1(j))) 9/22/2018

72 2.6 String Abstract Data Type(Cont’)
void String::fail() //compute the failure function for the pattern p(*this) { int LengthP = Length(); f[0]= -1; for(int j=1; j<LengthP; j++) //compute f[j] int i=f[j-1]; while ((*str+j) != (str+i+1))&&(i>=0)) i=f[j]; if(*str+j) == *(str+i+1)) f[j]=i+1; else f[j]= -1; } } //end of fail Program 2.16: Computing the failure function 9/22/2018


Download ppt "CH2. ARRAYS."

Similar presentations


Ads by Google