190 likes | 209 Views
Data Representation Methods. array --- Chapter 5 linked --- Chapter 6. 0. 1. 2. 3. 4. 5. 6. Linear List Array Representation. use a one-dimensional array element[]. a. b. c. d. e. L = (a, b, c, d, e) Store element i of list in element[i]. e. d. c. b. a.
E N D
Data Representation Methods array --- Chapter 5 linked --- Chapter 6
0 1 2 3 4 5 6 Linear List Array Representation use a one-dimensional array element[] a b c d e L = (a, b, c, d, e) Store element i of list in element[i].
e d c b a Right To Left Mapping
a b c d e Mapping That Skips Every Other Position
d e a b c Wrap Around Mapping
a b c d e 0 1 2 3 4 5 6 Representation Used In Text put element i of list in element[i] use a variablelistSizeto record current number of elements listSize = 5
listSize = 5 a b c d e listSize = 6 a g b c d e Insert/Erase An Element insert(1,g)
Data Type Of Array element[] Data type of list elements is unknown. Define element[]to be of template typeT.
Length of Array element[] Don’t know how many elements will be in list. Must pickan initial length and dynamically increase as needed. Use variable arrayLength to store current length of array element[].
a b c d e f Increasing Array Length Length of array element[] is 6. First create a new and larger array T* newArray = new T[15];
a b c d e f a b c d e f Increasing Array Length Now copy elements from old array to new one. copy(element, element + 6, newArray);
element[0] a b c d e f Increasing Array Length Finally, delete old array and rename new array. delete [] element; element = newArray; arrayLength = 15;
template<class T> void changeLength1D(T*& a, int oldLength, int newLength) { if (newLength < 0) throw illegalParameterValue(); T* temp = new T[newLength]; // new array int number = min(oldLength, newLength); // number to copy copy(a, a + number, temp); delete [] a; // deallocate old memory a = temp; }
How Big Should The New Array Be? At least 1 more than current array length. Cost of increasing array length when array is full is Q(old length). Cost of n insert operations done on an initially empty linear list increases by Q(n2).
a b c d e f Space Complexity element[6] newArray = new char[7]; space needed = 2 * newLength – 1 = 2 * maxListSize – 1
a b c d e f a b c d e f Array Doubling Double the array length. newArray = new char[12]; Time for ninserts goes up byQ(n). Space needed =1.5*newLength. Space needed <= 3*maxListSize – 3
Resizing by an additive constant increases the cost ofnadd operations byQ(n2). How Big Should The New Array Be? Resizing by any constant factor new length = c * old length increases the cost of ninserts by Q(n).
How Big Should The New Array Be? Resizing by any constant factor new length = c * old length requires at most (1+c) * (maxListSize -1)space. Resizing by an additive constant crequires at most (maxListSize – 1) + (maxListSize – 1 + c) = 2 * (maxListSize – 1) + c space.
What Does C++ Do? STL class vector … c = 1.5 arrayList of text … c = 2