1.13k likes | 1.4k Views
Chapter 2. Array. Overview. ADT of Array Sequence List ADT of Polynomial Special Array and Sparse Array String STL vector , deque , list and string. What is an array?. Array :
E N D
Chapter 2 Array Software College Northeastern University
Overview • ADT of Array • Sequence List • ADT of Polynomial • Special Array and Sparse Array • String • STL vector, deque,list andstring Software College Northeastern University
What is an array? Array: The basic mechanism for storing a collection of identically-typed objects. √ × Software College Northeastern University
The character of array • it is linear structure • Each element except the first has a unique predecessor, and each element except the last has a unique successor. • Given the size of the element and the start address, we can know the address of any element Software College Northeastern University
Definition and initialization • Two way to Define an array: static array,dynamic array • Example #include <iostream.h> class szcl { int e; public: szcl ( ) { e = 0; } szcl ( int value ) { e = value; } int get_value ( ) { return e; } } Software College Northeastern University
Static array main( ) { szcl a1[3] = { 3, 5, 7 }, *elem; for ( inti = 0;i < 3;i++ ) cout << a1[i].get_value ( ) << “\n”; //print the static array elem = new szcl[3]; for ( inti = 0;i < 3;i++ ) { cout << elem->get_value( ) << “\n”; //print the dynamic array elem++; } return 0; } Dynamic array Software College Northeastern University
Primitive arrays can’t satisfy us • We expect a copy of an array to copy the entire collection • We expect an array to know how many objects are in its collection • We expect that when allocated arrays are no longer needed, the memory that these arrays consumes is automatically reclaimed ....... How to do ? Software College Northeastern University
ADT of Array —— Class Declaration #include <iostream.h> #include <stdlib.h> template <class Type> class Array { Type*elements; int ArraySize; //current size void getArray ( ); // dynamic allocate memory for array public: Array(int Size=DefaultSize ); Array(constArray<Type>& x ); Software College Northeastern University
~Array( ){ delete [ ]elements;} Array<Type> & operator =//copy array ( constArray<Type>& A ); Type& operator [ ] ( int i ); //get the ith element Type* operator *( )const //* operator { returnelements; } int Length ( )const //get the length { return ArraySize; } void ReSize( int sz ); //resize the array } Software College Northeastern University
The interfaces of array class template <class Type> voidArray<Type>::getArray ( ){ //private function, create the space to store the elements elements = new Type[ArraySize]; if ( elements == 0 ) { ArraySize = 0; cerr << "Memory Allocation Error" << endl; return; } Software College Northeastern University
template <class Type> Array<Type>::Array ( int sz ){ //constructor if ( sz <= 0 ) { ArraySize = 0; cerr << “非法数组大小”<<endl; return; } ArraySize = sz; getArray ( ); } Software College Northeastern University
template <class Type> Array<Type>:: Array ( const Array<Type> & x ){ //copy constructor int n = ArraySize = x.ArraySize; elements = new Type[n]; if ( elements == 0 ) { ArraySize = 0; cerr<< “存储分配错”<< endl; return; } Type *srcptr = x.elements; Type*destptr = elements; while( n-- ) * destptr++ = * srcptr++; } Software College Northeastern University
template <class Type> Type & Array<Type>::operator [ ] ( int i ){ //get the element by index if ( i < 0|| i > ArraySize-1 ) { cerr << “数组下标超界”<<endl; return NULL; return element[i]; } Pos = Position[i -1] + Number[i -1] Software College Northeastern University
template <class Type> void Array<Type>::Resize (int sz) { if ( sz >= 0 && sz != ArraySize ) { Type * newarray = new Type[sz]; if ( newarray == 0 ) { cerr << “存储分配错”<< endl; return; } int n = ( sz <= ArraySize ) ? sz : ArraySize; Type *srcptr = elements; Type *destptr = newarray; while ( n--) * destptr++ = * srcptr++; delete [ ]elements; elements = newarray; ArraySize = sz; } } Software College Northeastern University
Two-dimensional array three-dimensional array column index i page index i rowindexj row indexj columnindexk Software College Northeastern University
One-dimensional array LOC ( i ) = LOC ( i -1 ) + l =α+ i*l Software College Northeastern University
Two-dimensional array Row major order: LOC ( i, j ) = a + ( i * m + j ) * l Column major order:LOC ( i, j ) = a + ( j * n + i ) * l Software College Northeastern University
Three-dimensional array • dimension values are m1, m2, m3 • the address of the element associated with index i, j, k LOC ( i, j, k ) = a + ( i *m2*m3+j*m3+ k )* l Software College Northeastern University
n-dimensional array • dimension values are m1, m2, m3, …, mn • the address of the element associated with index i1, i2, i3, …, in LOC ( i1, i2, …, in ) = a + ( i1*m2*m3*…*mn + i2*m3*m4*…*mn+ …… + in-1*mn + in ) * l Software College Northeastern University
Test • We store a 5×5 matrix A into an array B(index starts from 0) with column major order, the index of element a[3][2] in B is . • ( )For the following program fragment the running time(Big-Oh) is . • i = 0; • s = 0; • while( i < n ) • { i++; • s = s + i;} • a. O(n) b. O(n2) c. O(n1/2) d. O(n3) S Software College Northeastern University
a0 a1 ai-1 ai ai+1 an-1 Sequence list Using consecutive set of memory locations (Array) Address of element ai Loc(ai ) = Loc( a0 )+ i × L · Random-access storage Sequential mapping Software College Northeastern University
Implementation:Sequence list Sequence list :Dynamic array template <class Type> classSeqList { Type *data; int MaxSize; intlast; //index of the last element public: SeqList ( int MaxSize = defaultSize ); ~SeqList ( ){ delete [ ] data; } int Length ( )const{ returnlast+1;} int Find( Type& x ) const; Software College Northeastern University
Interface of sequence list int IsIn ( Type& x ); intInsert( Type & x, inti ); intRemove( Type& x ); int Next( Type& x ) ; int Prior( Type& x ) ; int IsEmpty ( ){ returnlast ==-1;} intIsFull ( ){ return last == MaxSize-1;} Type Get(int i ) { returni < 0|| i > last?NULL:data[i]; } } Software College Northeastern University
Implementation of sequence list template <class Type> SeqList<Type> :: SeqList ( int sz ) { //constructor if ( sz > 0 ){ MaxSize = sz; last = -1; data = new Type[MaxSize]; if ( data == NULL ) { MaxSize = 0; last = -1; return; } } } Software College Northeastern University
template <class Type> intSeqList<Type>::Find ( Type& x ) const { //sequence find x from begin to end int i = 0; while( i <= last && data [i]!= x ) i++; if ( i > last ) return-1; //failure else return i; //success } Software College Northeastern University
template <class Type> intSeqList<Type>::IsIn ( Type& x ) { //Is x in the List? int i = 0, found = 0 while( i <= last &&! found ) if( data[i] ! =x )i++; elsefound = 1; //success return found; } Software College Northeastern University
Diagram of finding x = 48 x = 50 Software College Northeastern University
Success: • Average Comparing Number • Failure: n Software College Northeastern University
Insertion 如何移动? for (int j = i; j <=last; j++) data[j+1] = data[j ]; How to move? for (int j = last+1; j >i; j-- ) data[j] = data[j - 1]; Software College Northeastern University
template <class Type> intSeqList<Type>::Insert (Type& x,inti ){ //insert x into the list as the ith element if ( i < 0||i > last+1||last == MaxSize-1 ) return 0; //failure else { last++; for (int j = last; j > i; j-- ) data[j] = data[j -1]; data[i] = x; return 1; //success } } Software College Northeastern University
deletion Software College Northeastern University
template <class Type> intSeqList<Type>::Remove (Type& x ) { //delete x from the list inti = Find (x); //find x if ( i >= 0) { last-- ; for ( int j = i; j <= last; j++ ) data[j] = data[j+1]; return 1; //succeed } return 0; //failure } Software College Northeastern University
template <class Type> intSeqList<Type>:: Next(Type& x ) { //Gets the next element in list. inti = Find (x); //find x if ( i >= 0 && i < last) return i + 1; else return -1; //failure } template <class Type> intSeqList<Type>:: Prior(Type& x ) { //gets the predecessor inti = Find (x); //find x if ( i >= 0 && i <= last) return i - 1; else return -1; } Software College Northeastern University
顺序表用数组实现的操作的特点 • 1.通过元素的存储顺序反映线性表中 • 数据元素之间的逻辑关系; • 2.可随机存取顺序表的元素; • 3.顺序表的插入、删除操作要通过移动元素实现,效率较低; • 4.元素较少时存储空间的利用率较低。 Software College Northeastern University
Application:sequence list Example2-1:using sequence list to resolve the union of two set A and B A= A∪ B idea: (1)use type SqList to store set LA and LB (2)get element from LB not existent in LA,add them to LA B A Software College Northeastern University
Application:sequence list template <class Type> voidUnion ( SeqList<Type>& LA, SeqList<Type> LB ) { int n = LA.Length ( ); int m = LB.Length ( ); for ( int i = 1; i <= m; i++ ) { Type x = LB.Get(i); //在LB中取一元素 int k = LA.Find (x); //在LA中搜索它 if ( k == -1 ) //若未找到插入它 { LA.Insert (n+1, x); n++; } } } Time complexity:O(ListLength(La)*ListLength(Lb)) 4 3 B A 2 1 Software College Northeastern University
Application:sequence list Example2-2:using sequence list to compute A-B idea: (1)use type SqList to store ordered list (2) Delete the element which isn’t in other list through comparing B A Software College Northeastern University
Application:sequence list template <class Type> void Intersection ( SeqList<Type>& LA, SeqList<Type>& LB ) { int n = LA.Length ( ); int m = LB.Length ( ); int i = 0; while ( i < n ) { Type x = LA.Get (i); int k = LB.Find (x); if ( k == -1 ) { LA.Remove (x); n--; } else i++; } } Software College Northeastern University
ADT of Polynomial P(x) = p0 + p1 x + p2 x2 + … + pn xn Q(x) = q0 + q1 x + q2 x2+ … + qm xm Addition of two polynomials ,suppose m<n R(x)=(p0+q0)+(p1+q1)x+…+(pn+qm)xm+pm+1 xm+ … +pn xn P = (p0, p1, p2 , …pn) Q = (q0, q1, q2, …qm) R = (p0+q0, p1+q1, …, pm+qm, pm+1, …, pn ) Software College Northeastern University
Polynomial ADT class Polynomial{ public: Polynomial ( ); int operator !( ); //if *thisis zero , return 1. else return 0 float Coef ( int e); //return coefficient of the item with e exponent intLeadExp ( ); //return the max exponent PolynomialAdd (Polynomialpoly); PolynomialMult (Polynomial poly); float Eval ( floatx); } Software College Northeastern University
Physical representation First :private: (static int degree; array)float coef [maxDegree+1]; Pn(x): pl.degree = n pl.coef[i] = ai, 0 in Software College Northeastern University
Second:private: (dynamicintdegree; Array )float * coef; Polynomial::Polynomial (intsz) { degree = sz; coef = new float [degree + 1]; } Pn(x): pl.degree = n pl.coef[i] = ai, 0 in Software College Northeastern University
Some polynomial only have few nonzero coefficents : P101(x) = 3 + 5x50 - 14x101 pl.degree = 101 pl.coef = new float[102] Method: Only store the nonzero item Software College Northeastern University
第三种: classPolynomial; class term {//多项式的项定义 friend Polynomial; private: float coef; //系数int exp; //指数 }; Software College Northeastern University
class Polynomial { public: …… private: static term termArray[MaxTerms]; static int free; //current address of free space // termPolynomial::termArray[MaxTerms]; // int Polynomial::free = 0; int start, finish; } Software College Northeastern University
A(x) = 2.0x1000+1.8 B(x) = 1.2 + 51.3x50 + 3.7x101 store two polynomials in termArray Software College Northeastern University
Add two polynomials • 结果多项式另存 • 扫描两个相加多项式,若都未检测完: • 若当前被检测项指数相等,系数相加。 若未变成 0,则将结果加到结果多项式。 • 若当前被检测项指数不等,将指数小者加到结果多项式。 • 若有一个多项式已检测完,将另一个多项式剩余部分复制到结果多项式。 Software College Northeastern University
Polynomial Polynomial::operator+(Polynomial B) { Polynomial C; inta = start;intb = B.start;C.start = free; float c; // coefficient of result polynomial while ( a <= finish && b <= B.finish ) switch( compare ( termArray[a].exp, termArray[b].exp) ) {//compare exponents case ‘=’ : //with the same exponents c = termArray[a].coef + //add two exponents termArray[b].coef; if ( c ) NewTerm ( c, termArray[a].exp ); a++; b++;break; Software College Northeastern University
case ‘>’ : NewTerm ( termArray[b].coef, termArray[b].exp ); b++;break; case '<': NewTerm ( termArray[a].coef, termArray[a].exp ); a++; } for ( ; a <= finish; a++ ) NewTerm ( termArray[a].coef, termArray[a].exp ); Software College Northeastern University
for ( ; b <= B.finish; b++ ) NewTerm ( termArray[b].coef, termArray[b].exp ); C.finish = free-1; returnC; } Software College Northeastern University