advance data structure review of chapter 2 張啟中. review of chapter 2 arrays 1.3 data...
TRANSCRIPT
Advance Data StructureReview of Chapter 2
張啟中
Review of Chapter 2 Arrays
1.3 Data Abstraction and Encapsulation 2.2 The Array As An abstract Data Type
2.5 The Representation of Arrays Example
2.3 The Polynomial Abstract Data Type 2.4 The Sparse Matrix Abstract Data Type 2.6 The String Abstract Data Type
定義:定義: Data TypeData Type
A data type is a collection of objects and a set of operations that act on those objects.
定義:定義: Abstract Data TypeAbstract Data Type
An abstract data type(ADT) is a data type that is organized in such a way that the specification of the objects and the operations on the objects is separated from the representation of the objects and the implementation of the operations.
資料型態 Data Types Primitive Data Types Accumulated Data
Types- Array- Structures- Union
Abstract Data Types Examples
Example: Data Type of C++Name of Type # of bits Range Type
char 8 -128 ~ 127 字元
unsigned char 8 0 ~ 255 字元
short 16 -215 ~ 215 - 1 短整數
unsigned short 16 0 ~ 216 - 1 正短整數
int 32 -231 ~ 231 - 1 整數
unsigned 32 0 ~ 231 - 1 正整數
long 32 -231 ~ 231 - 1 長整數
unsigned long 32 0 ~ 231 - 1 正長整數
float 32 -1037 ~ 1037 浮點數
double 64 -10308 ~ 10308 倍準浮點數
表一: C++ 的基本資料型態
Accumulated Data Type
Array
Struct
Union
如何理解 Abstract Data Types
ADTs 是一個物件的型態的抽象定義具有一般化的特性,其中也包含這個物件相關的操作。
Data Structures 課程,旨在瞭解每一個 ADT ,要用什麼樣的結構來表達與儲存,而這樣的表達與儲存方式,又對於該物件的操作帶來什麼樣的優缺點。亦即關注在二個重點: 物件儲存與表達方式(資料結構) 物件操作方式(演算法)
The Array as an Abstract Data Type
Array A collection of data of the same type An array is usually implemented as a
consecutive set of memory locations int list[5], *plist[5]
ADT definition of an Array More general structure than "a consecutive set
of memory locations.“ An array is a set of pairs, <index, value>, in
mathematical, call correspondence or mapping
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. 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
Array (陣列)
陣列是用來存放同樣型態的資料 陣列的大小必須在程式中預先設定 在程式執行中,陣列的大小無法改變 陣列中的資料是透過索引( index )來存取
const int ArraySize = 100;
int iArray[ArraySize];
一維陣列和記憶體間的對應
int iArray[100];
7 51 22 43 9
0 1 2 98 99
m
m + 2
m + 4
m + 6
m + 198
假定 sizeof(int) = 2
Memory
多維陣列和記憶體間的對應
0
1
2
3
4
5
6
0 1 2 3 4 5 6 7 8 9 10
int mesh[7][11];
m
m + 22
m + 44
m + 66
m + 88
m + 110
m + 132
假定 sizeof(int) = 2
Memory
mesh[i][j] = mesh +11 i + j
多維陣列的宣告
typetype array_name[arraySizearray_name[arraySize11] ...... [arraySize] ...... [arraySizenn];];
【範例】
int mesh[7][11];
0123456
0 1 2 3 4 5 6 7 8 9 10
float cube[6][8][3];
0 1 2 3 4 5 6 7012345
01
2
float cube[6][8][3];
0 1 2 3 4 5 6 70
123
4
5
01
2
m
m + 48
m + 96
m + 144
m + 192
m + 240
m + 288
假定 sizeof(int) = 2cube[i][j][k] = cube + 24i + 8j+ k
struct 和記憶體間的對應
struct studentType { char Name[20]; // 姓名 char Address[30]; // 地址 char PhoneNumber[10]; // 電話 int Age; // 年齡 char Department[4]; // 系別 int Year; // 年級 char Class; // 班級};
studentType Student1, Student2;
m
m + 20
m + 50
m + 66
m + 60
m + 62
m + 68
假定 sizeof(int) = 2
Self-Referential Structures
One or more of its components is a pointer to itself.
typedef struct list {char data;list *link;}
list item1, item2, item3;item1.data=‘a’;item2.data=‘b’;item3.data=‘c’;item1.link=item2.link=item3.link=NULL;
Construct a list with three nodesitem1.link=&item2;item2.link=&item3;malloc: obtain a node
a b c
union 的宣告
union { field1 declaration; field2 declaration;
} variable_name;
typedef union { field1 declaration; field2 declaration;
} type_name;
【範例】union { char charValue; int intValue; float floatValue;} dataCell;
typedef union { char charValue; int intValue; float floatValue;} dataCellType;
宣告變數 宣告型態
union 和記憶體間的對應union { char charValue; /* 1 byte */ int intValue; /* 2 byte */ float floatValue; /* 4 byte */} dataCell;
m
m + 4
typedef struct { char opcode; union { int intValue; char strValue[256]; } data;} instruction;
m
m + 257
m+1
m+5
Example Ordered List Polynomial ADT Sparse Matrix ADT String ADT
Ordered List Examples
(MONDAY, TUEDSAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAYY, SUNDAY)
(2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King, ACE) (1941, 1942, 1943, 1944, 1945) (a1, a2, a3, …, an-1, an) ()
ordered (linear) list: (item1, item2, item3, …, itemn)
Operations on Ordered List Find the length, n , of the list.
Read the items from left to right (or right to left). Retrieve the i’th element. Store a new value into the i’th position. Insert a new element at the position i , causing element
s numbered i, i+1, …, n to become numberedi+1, i+2, …, n+1
Delete the element at position i , causing elements numbered i+1, …, n to become numbered i, i+1, …, n-1
array (sequential mapping)? (1)~(4) O (5)~(6) X
Polynomial (多項式)
P x a x a x a x a
a x
nn
nn
kk
k
n
( )
11
1 0
0
6 4 2 1
7 2 4
13 2 5
3 2
3 2
3 2
x x x
x x x
x x x
Addition:
( )( )
( )
2 2 2 1
4 2 2 1 4 2
4 2 2 3 2
3
4 3 2
4 3 2
x x x
x x x x
x x x x
Multiplication:
class Polynomial { // objects: p(x) = a0
xe0 + … + anxen; a set of ordered pairs of <ei, ai>, where
// ai ∈ Coefficient and ei ∈ Exponent // We assume that Exponent consists of integer ≥ 0public: 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
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
Polynomial: Representation 1
Representation by Degreesprivate
int degree; // degree MaxDegree
float coef [MaxDegree + 1]; Example:
Let A(x)=Σaixi , then
a.degree= n,
a.coef[i]=an-i, ,0<= i<= n
Polynomial: Representation 1
P x a x a x ann( ) 1 0
a0a12naan 1an
0 1 2 n-1 n
ndegree
coef
Polynomial: Representation 2
Representation by Degrees, but dynamic allocation spaceprivate:
int degreedegree; //degree <= MaxDegree
float *coefcoef;
polynomial::polynomial(int d)
{
degree= d,
coef=new float[degree+1];
}
Polynomial: Representation 3 Representation by Terms.
Class polynomial;Class term { Friend polynomial; private:
int exp float coefcoef;
};
In polynomial class
In Implement file of polynomial class
private: static term termArray[MaxTerms]; // MaxTerms is a constant. // termArray[MaxTerms] shared by all polynomial objects. static int free; int start, finish;
term Polynomial::termArray[MaxTerms];int polynomial::free = 0;
A(X)=2X1000+1B(X)=X4+10X3+3X2+1
2 1 1 10 3 1
1000 0 4 3 2 0coef
exp
A.start A.finish B.start B. finish free
0 1 2 3 4 5 6
Polynomial: Representation 3-1
In general, In general, A.FinishA.Finish = = A.StartA.Start + + nn –1. –1. For For zero polynomialzero polynomial, , A.FinishA.Finish = = A.StartA.Start – 1 – 1
Polynomial: Representation 3-2
P x c x c x c x e e ee ek
ek
k( ) , 1 2 1 21 2
c1 c2 c3 ck
0 1 2 k-1
knumTerm
coef ?
e1 e2 e3 ek
0 1 2 k-1
expon ?
The Representations of Polynomials Compare
Representation 1 Representation 2 Representation 3
AdvantagesSimply algorithms for
most operationsSave space than R1
Save space when polynomial is sparse
than R1, R2
Disadvantages
Waste spaces
if a.degree << MaxDegree
Waste spaces when
polynomial is sparse
Waste twice space when all terms are nonzero than R2 , and algorithms is comple
x than R1, R2
操作分析
多項式相加 As Representation 3 , we take O(m+n) at time complexity , if
A(x) has m terms, B(x) has n terms. See Book pp.83-84
多項式相乘
0002800
0000091
000000
006000
0003110
150220015col1 col2 col3 col4 col5 col6
row0
row1
row2
row3
row4
row5
(a) (b)
*Figure 2.3:Two matrices
8/36
6*65*3
15/15
Sparse Matrix
sparse matrixdata structure?
若以二維陣列的表示法:#define MAX_ROW 100
#define MAX_COL 100
typedef int matrix[MAX_ROW][MAX_COL];
matrix m1, m2;
來儲存稀疏矩陣,那麼,矩陣中含有許多的 0 。有沒有必要儲存這些 0 呢?有沒有比較節省記憶體空間的另類表示法?
Abstract Data Type Sparse Matrixclass SparseMatrix{ //objects: a set of triples, <row, column, value>, where row and column are integers and // form a unique combination, and value comes from the set item. public: SparseMatrix(int MaxRow, int MaxCol); //create a SparseMatrix that can hold up to MaxItems= MaxRow*MaxCol and whose //maximum row size is MaxRow and whose maximum column size is MaxCol
SparseMatrix TransposeTranspose(); // return the matrix produced by interchanging the row and column value of every triple.
SparseMatrix AddAdd(SparseMatrix b); //if the dimensions of a(*this) and b are the same, return the matrix produced by adding //corresponding items, namely those with identical row and column values. else return //error.
SparseMatrix MultiplyMultiply(a, b); //if number of columns in a equals number of rows in b return the matrix d produced by //multiplying a by b according to the formula: d[i][j]= Sum(a[i][k](b[k][j]), //where d(i, j) is the (i, j)th element, k=0 ~ ((columns of a) –1) else return error. };
Representation of Sparse Matrixclass SparseMatrix;class MatrixTerm {
friend class SparseMatrix private: int col, row, value;};
In class SparseMatrix private:
int col, row,Terms; MatrixTerm smArray[MaxTerms]; // Note: triples are ordered by rowrow and within rows by columnscolumns
row col valuea[0] 0 0 15a[1] 0 3 22a[2] 0 5 -15a[3] 1 1 11a[4] 1 2 3a[5] 2 3 -6a[6] 4 0 91a[7] 5 2 28
15 0 0 22 0 -15 0 11 3 0 0 0 0 0 0 -6 0 0 0 0 0 0 0 091 0 0 0 0 0 0 0 28 0 0 0
row 0row 1row 2row 3row 4row 5
0 1 2 3 4 5
termcol
Sparse Matrix 運算分析
轉置 (transpose) 相加 相乘
Class String{ //objects: a finite set of zero or more characters. public: String (char *init, int m); //Constructor that initializes *this to string init of length is m. int operator==(string t); // if the string represented by *this equal string t return 1(true) else return 0(false) int operator!(); // if *this is empty then return 1(TRUE); else return 0 (FALSE). int LengthLength(); //return the number of characters in *this. String ConcatConcat(String t); //return a string whose elements are those of *this followed by those of t. String SubstrSubstr(int i, int j); //return the string containing j characters of *this at positions i, i+1, ..., i+j-1, //if these are valid positions of *this; else return 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.};
Abstract Data Type String
Pattern Matching
Given two strings, string and pat, where pat is a pattern to be searched for in string
Two methods a simple algorithm
O(S*P) O(n2) optimal algorithm (by Knuth-Morris-Pratt)
Linear complexity O(S+P) O(n)
a a b pattern
a b a b b a a a a a no match
a b a b b a a b a a match
O(n*m)
A simple algorithm
a a b pattern
The Failure Function
Definition If p= p0p1. . .pn-1 is a pattern, then its failure function, f is defined as:
f(j) = largest i< j such that p0p1. . .pi= pj-ipj-i+1. . .pj , i>= 0
= -1, otherwise
Example
j 0 1 2 3 4 5 6 7 8 9pat a b c a b c a c a b f -1 -1 -1 0 1 2 3 -1 0 1
Rule for Optimal Pattern Matching If a partial match is found such that si-j. . .si-1= p0p1. . .pj-1 a
nd si<>pj then matching may be resumed by comparing si and pf(j-1)+1 if j<>0. If j= 0, continue by comparing si+1 and p0
string a b c a ? ? . . . ? pat a b c a b c a c a b f -1 -1 -1 0 1 2 3 -1 0 1
Continue here
Example of Optimal Pattern Matching
j 0 1 2 3 4 5 6 7 8 9pat a b c a b c a c a b f -1 -1 -1 0 1 2 3 -1 0 1
str c b a b c a str c b a b c a aa b c a b c a b c a b c a b b c a c a bc a c a b