Chapter 2 1. Arrays Array: a set of index and value Data structure For each index, there is a value associated with that index. Eg. int list[5]: list[0],

Slides:



Advertisements
Similar presentations
Linear Lists – Array Representation
Advertisements

Lists: An internal look
Arrays 2008, Fall Pusan National University Ki-Joune Li.
1 Linked Lists Gordon College Prof. Brinton. 2 Linked List Basics Why use? 1.Efficient insertion or deletion into middle of list. (Arrays are not efficient.
Array pair C++ array requires the index set to be a set of consecutive integers starting at 0 C++ does not check an array index to ensure that it belongs.
Data Abstraction and Encapsulation
Chapter 4 Systems of Linear Equations; Matrices Section 2 Systems of Linear Equations and Augmented Matrics.
CHAPTER 10 ARRAYS II Applications and Extensions.
Dictionaries and Hash Tables1  
Chapter 4.
Chapter 2. C++ Class A class name Data members Member functions Levels of program access –Public: section of a class can be accessed by anyone –Private:
Department of Computer Eng. & IT Amirkabir University of Technology (Tehran Polytechnic) Data Structures Lecturer: Abbas Sarraf Arrays.
Hash Tables1 Part E Hash Tables  
Hash Tables1 Part E Hash Tables  
CHAPTER 6 Stacks Array Implementation. 2 Stacks A stack is a linear collection whose elements are added and removed from one end The last element to be.
C++ for Engineers and Scientists Third Edition
Matrix table of values
MATRICES. Matrices A matrix is a rectangular array of objects (usually numbers) arranged in m horizontal rows and n vertical columns. A matrix with m.
Chapter 4 1. Why “linked lists” 2 IndexWord A[0]BAT A[1]CAT A[2]EAT … A[n]WAT Insert “FAT” ? Or delete something.
 Row and Reduced Row Echelon  Elementary Matrices.
Chapter 7: Arrays. In this chapter, you will learn about: One-dimensional arrays Array initialization Declaring and processing two-dimensional arrays.
Data Structure (Part I) Chapter 2 – Arrays Data Abstraction and Encapsulation in C++ Section 1.3 –Data Encapsulation Also called information hiding.
Chapter 3: The Fundamentals: Algorithms, the Integers, and Matrices
CSCE 3110 Data Structures & Algorithm Analysis Arrays and Lists.
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 3 Lists, Stacks, and Queues §1 Abstract Data Type (ADT) 【 Definition 】 Data Type = { Objects }  { Operations } 〖 Example 〗 int = { 0,  1, 
Advance Data Structure Review of Chapter 2 張啟中. Review of Chapter 2 Arrays 1.3 Data Abstraction and Encapsulation 2.2 The Array As An abstract Data Type.
Data Structure (Part II) Chapter 2 – Arrays. Matrix A matrix with 5 rows and 3 columns can be represented by n = 3 m = 5 We say this is a 5×3 matrix.
Data Strcutures.
Chapter 4 – Matrix CSNB 143 Discrete Mathematical Structures.
Hash Tables1   © 2010 Goodrich, Tamassia.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Arrays.
Linked List (Part II). Introduction  Definition of equivalence relation: A relation ≡ over a set S, is said to be an equivalence relation over S iff.
Data Structure Sang Yong Han Chung-Ang University Spring
Data Structures & Algorithm Analysis Arrays. Array: a set of pairs (index and value) data structure For each index, there is a value associated with that.
© 2004 Goodrich, Tamassia Hash Tables1  
Sparse Vectors & Matrices Jyh-Shing Roger Jang ( 張智星 ) CSIE Dept, National Taiwan University.
1 String Processing CHP # 3. 2 Introduction Computer are frequently used for data processing, here we discuss primary application of computer today is.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
Data Structures Chapter 2: Arrays 2-1. Four components in a C++ Class –class name –data members: the data that makes up the class –member functions: the.
UNIT 10 Multidimensional Arrays.
1 Chapter 13-2 Applied Arrays: Lists and Strings Dale/Weems.
Data Structure Specification  Language independent  Abstract Data Type  C++  Abstract Class.
Sparse Matrices Matrix  table of values. Sparse Matrices Matrix  table of values Row 2 Column 4 4 x 5 matrix.
Java – An Object Oriented Language CS 307 Lecture Notes Lecture Weeks 5-6 Khalid Siddiqui.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved More Linking.
1. 2  Introduction  Array Operations  Number of Elements in an array One-dimensional array Two dimensional array Multi-dimensional arrays Representation.
1 Data Structures CSCI 132, Spring 2014 Lecture 33 Hash Tables.
Arrays Declaring arrays Passing arrays to functions Searching arrays with linear search Sorting arrays with insertion sort Multidimensional arrays Programming.
Chap 2 Array ( 陣列 ). ADT In C++, class consists four components: –class name –data members : the data that makes up the class –member functions : the.
Arrays Department of Computer Science. C provides a derived data type known as ARRAYS that is used when large amounts of data has to be processed. “ an.
Chapter 8: Loops, Arrays, Strings Loop statements –do –while –for Arrays –declaration, allocation, initialization, access –multi-dimensional –heterogeneous.
1 ARRAYS AND STRUCTURES. 2 Arrays Array: a set of index and value data structure For each index, there is a value associated with that index. representation.
LINKED LISTS.
Programming Application in Civil Engineering
Data Structure Sang Yong Han
Computer Programming BCT 1113
More Linking Up with Linked Lists
CSCE 3110 Data Structures & Algorithm Analysis
Chap 2 Array (陣列).
Data Structures Unit-2 Engineered for Tomorrow CSE, MVJCE.
CH2. ARRAYS.
Instructor: Mr.Vahidipour
CSCE 3110 Data Structures & Algorithm Analysis
Linked List (Part I) Data structure.
2017, Fall Pusan National University Ki-Joune Li
2018, Fall Pusan National University Ki-Joune Li
Data Structures Chapter 4: Linked Lists.
Presentation transcript:

Chapter 2 1

Arrays Array: a set of index and value Data structure For each index, there is a value associated with that index. Eg. int list[5]: list[0], …, list[4] each contains an integer list

Abstract data type GeneralArray class GeneralArray { // A set of pairs 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), (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); // This constructor creates j dimension 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 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; otherwise throw an // exception. void Store(index i, float x); // If i is in the index set of the array, replace the old value associated with i by x; otherwise throw an // exception. }; // 3

Ordered (linear) list Eg. Days of the week: (SUN, MON, TUS, WED, THU, FRI, SAT) Values in a deck of cards: (Ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King) Floors of a building: (basement, lobby, mezzanine, first, second) Years the United States fought in World War II: (1941, 1942, 1943, 1944, 1945) 4

Operations on lists (1) Find the length, n, of the list. (2) Read the items from left to right (or right to left). (3) Retrieve the ith element, 0≤i<n. (4) Store a new value into the ith position, 0≤i<n. (5) Insert a new element at the position i, 0≤i<n, causing elements numbered i, i+1, …,n-1 to become numbered i+1, i+2, …, n. (6) Delete the element at position i, causing elements numbered i+1, …, n-1 to become numbered i, i+1, …,n-2. 5

Sequential mapping Most common way to represent an ordered list is by an array where we associate the list element a i with the array index i Performing operations (5) and (6) requires data movement Linked list in Chapter 4 6

The polynomial abstract data type The largest exponent of a polynomial is called is degree A polynomial is called sparse when it has many zero terms Implement polynomials by arrays 7

Abstract data type Polynomial class Polynomial { // p(x) = ; a set of ordered pairs of // where a i is a nonzero float coefficient and e i is a non-negative integer exponent. public: Polynomial( ); // Construct the polynomial p(x) = 0. 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. }; 8

Polynomial representation 1 private: int degree; // degree ≤ MaxDegree float coef [MaxDegree + 1]; // coefficient array Let a be a Polynomial class object and n≤MaxDegree a.degree=n a.coef[i]=a n-i, 0≤ i ≤n Eg. a(x)=3x 2 +2x-4 9 i012 coef[i]32-4

Polynomial representation 2 private: int degree; float *coef; Polynomial::Polynomial(int d) { degree=d; coef = new float[degree+1]; } 10

Polynomial representation 3 class Polynomial; class Term{ friend Polynomial; private: float coef; int exp; }; private: Term *termArray; // array of nonzero terms int capacity; // size of termArray int terms; // number of nonzero terms 11

Example: c(x)=2x coef21 exp termArray c.capacity=2 c.terms=2

Example a(x)=2x , b(x)=x 4 +10x 3 +3x a.starta.finishb.startb.finish coef exp

Polynomial addition Polynomial Polynomial::Add(Polynomial b) {// Return the sum of the polynomials *this and b. Polynomial c; int aPos = 0, bPos = 0; while ((aPos < terms) && (bPos < b.terms)) if (termArray [aPos].exp = = b.termArray [bPos].exp) { float t = termArray [aPos].coef + b.termArray [bPos].coef; If (t) c.NewTerm (t, termArray [aPos].exp); aPos++; bPos++; } else if (termArray [aPos].exp < b.termArray [bPos].exp) { c.NewTerm (b.termArray [bPos].coef, b.termArray [bPos].exp); bPos++; } else { c.NewTerm (termArray [aPos].coef,termArray [aPos].exp); aPos++; } // add in remaining terms of *this for ( ; aPos < terms ; aPos++) c.NewTerm (termArray [aPos].coef, termArray [aPos].exp); // add in remaining terms of b(x) for ( ; bPos < b.terms ; bPos++) c.NewTerm (b.termArray [bPos].coef, b.termArray [bPos].exp); return c; } 14

Adding a new term void Polynomial::NewTerm(const float theCoeff, const int theExp) {// Add a new term to the end of termArray if (terms = = capacity) {// double capacity of termArray capacity *= 2; term *temp = new term[capacity]; // new array copy(termArray, termArray + terms, temp); delete [] termArra ; // deallocate old memory termArray = temp; } termArray [terms].coef = theCoeff; termArray [terms++].exp = theExp; } 15

Sparse matrices A general matrix consists of m rows and n columns of numbers An m×n matrix It is natural to store a matrix in a two dimensional array, say A[m][n] A matrix is called sparse if it consists of many zero entries Implementing a spare matrix by a two dimensional array waste a lot of memory Space complexity is O(m×n) 16

Sparse matrices (b) (a)(b)

Abstract data type SparseMatrix class SparseMatrix {// A set of triples, public: SparseMatrix(int r, int c,int t); // The constructor function creates a SparseMatrix with r rows, c columns, and a capacity // of t nonzero terms SparseMatrix Transpose( ); // Returns the SparseMatrix obtained by interchanging the row and column value of every // triple in *this SparseMatrix Add(SparseMatrix b); // If the dimension of *this and b are the same, add; otherwise, an exception is thrown. SparseMatrix Multiply(SparseMatrix b); }; 18

Sparse matrix representation Use triple Must know the numbers of rows and columns and the number of nonzero elements 19 rowcolvaluerowcolvalue smArray[0]0015smArray[0]0015 [1]0322[1]0491 [2]05-15[2]1111 [3]1111[3]213 [4] [5]23-6[5]3022 [6]4091[6]32-6 [7]5228[7]50-15 (a)(b)

class SparseMatrix; // forward declaration class MatrixTerm { friend class SparseMatrix private: int row, col, value; }; In class SparseMatrix: private: int rows, cols, terms, capacity; MatrixTerm *smArray[MaxTerms]; 20

Transposing a matrix For each row i take element and store it in element of the transpose. difficulty: where to put (0, 0, 15) ====> (0, 0, 15) (0, 3, 22) ====> (3, 0, 22) (0, 5, -15) ====> (5, 0, -15) (1, 1, 11) ====> (1, 1, 11) Move elements down very often. For all elements in column j, place element in element 21

Iteration 0: scan the array and process the entries with col=0 22 Reference: J.L.

Iteration 1: scan the array and process the entries with col=1 23 Reference: J.L.

Transposing a matrix SparseMatrix SparseMatrix::Transpose( ) {// Return the transpose of *this SparseMatrix b(cols, rows, terms); // capacity of b.smArray is terms 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 and move terms in column c if (smArray[i].col = = c) { b.smArray[currentB].row = c; b.smArray[currentB].col = smArray[i].row; b.smArray[currentB++].value = smArray[i].value; } } // end of if (terms > 0) return b; } 24

Transposing a matrix faster Store some information to avoid scanning all terms back FastTranspose requires more space than Transpose Calculate RowSize by scanning array b Calculate RowStart by scanning RowSize 25

Example 26

27 1

28 7

29 Reference: J.L.

Transposing a matrix faster SparseMatrix SparseMatrix::FastTranspose( ) {// Return the transpose of *this in O(terms + cols) time. SparseMatrix b(cols, rows, terms); if (terms > 0) {// nonzero matrix int *rowSize = new int[cols]; int *rowStart = new int[cols]; // compute rowSize[i] = number of terms in row i of b fill(rowSize, rowSize + cols, 0); // initialize for (int i = 0 ; i < terms ; i ++) rowSize[smArray[i].col]++; // rowStart[i] = starting position of row i of b rowStart[0] = 0; for (int i = 1 ; i < cols ; i++) rowStart[i] = rowStart[i-1] + rowSize[i-1]; 30

for (int i = 0 ; i < terms ; i++) {// copy from *this 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]++; } delete [] rowSize; delete [] rowStart; } return b; } 31

Multidimensional arrays Row major order Eg. A[2][3][2][2] 24 elements (2 x 3 x 2 x 2 = 24) a[0][0][0][0], a[0][0][0][1], a[0][0][1][0], a[0][0][1][1] a[0][1][0][0], a[0][1][0][1], a[0][1][1][0], a[0][1][1][1] … a[1][2][0][0], a[1][2][0][1], a[1][2][1][0], a[1][2][1][1] 32

Two dimensional array row major order 33

Generalizing array representation Declare a[u 1 ][u 2 ]…[u n ] The address for a[i 1 ][i 2 ]…[i n ] is 34 where α is the address of a[0][0], a n =1 and a j =1≤j<n

Abstract data type String class String { public: String(char *init, int m); // Constructor that initializes *this to string init of length m. bool operator = = (String t); // If the string represented by *this = t, return true, else return false. bool operator!( ); // If *this is empty, return true, else return false. int Length( ); // Return the number of characters in *this. String Concat(String t); // Return *this + t 。 String Substr(int i, int j); // Return a string containing the j characters of *this at position i, i + 1,..., i + j - 1 if these are valid position of *this; // otherwise, throw an exception. int Find(String pat); // Return an index i such that pat matches the substring of *this that begins at position i. // Retrun -1 if pat is either empty or not a substring of *this. }; 35

String matching Input: P and T, the pattern and text strings; m and n, the length of P and T, respectively. The pattern is assumed to be nonempty. Output: The return value is the index in T where a copy of P begins, or -1 if no match for P is found. 36 Reference: J.L.

The Knuth-Morris-Pratt algorithm (KMP algorithm) Suppose that pat=abcabcacab and s=s 0 s 1 …s m-1 37 abcabcacab abcaa abcabcacab abcaa Restart scanning here

Failure function If p=p 0 p 2 …p n-1 is a pattern, then its failure function, f, is defined as f(j) = largest k<j such that p 0 …p k = p j-k …p j if such a k≥0 exists f(j) = -1 otherwise Eg. 38 j patabcabcacab f

Example j=0 Since k<0 and k ≧ 0, no such k exists f(0)= -1 j=1 k<1 and k ≧ 0, thus k=0 When k=0  p 0 =a and p 1 =b  p 0 ≠p 1 f(1)= j patabcabcacab f f(j) = largest k<j such that p 0 …p k = p j-k …p j if such a k≥0 exists f(j) = -1 otherwise

Example j=2 Since k<2 and k ≧ 0, k=0,1 When k=1  p 0 p 1 =ab and p 1 p 2 =bc  p 0 p 1 ≠p 1 p 2 When k=0  p 0 =a and p 2 =c  p 0 ≠p 2 f(2)= -1 j=3 Since k<3 and k ≧ 0, k=0,1,2 When k=2  p 0 p 1 p 2 =abc and p 1 p 2 p 3 =bca When k=1  p 0 p 1 = ab and p 2 p 3 =ca When k=0  p 0 =a and p 3 =a  p 0 =p 3 f(3)= 0 40 j patabcabcacab f f(j) = largest k<j such that p 0 …p k = p j-k …p j if such a k≥0 exists f(j) = -1 otherwise

Example j=4 k<4 and k ≧ 0, thus k = 0, 1, 2, 3 When k=3  p 0 p 1 p 2 p 3 =abca and p 1 p 2 p 3 p 4 =bcab When k=2  p 0 p 1 p 2 =abc and p 2 p 3 p 4 =cab When k=1  p 0 p 1 =ab and p 3 p 4 =ab f(4)=1 41 j patabcabcacab f f(j) = largest k<j such that p 0 …p k = p j-k …p j if such a k≥0 exists f(j) = -1 otherwise

Fast matching Suppose that pat=abcabcacab and s=abcaa… 42 abcabcacab abcaa posP j patabcabcacab f Failure function Step 1: fail at posP=4 (=posS) Step 2: check f(3) Step 3: posP=pat.f[posP-1]+1 = pat.f[3]+1 =0+1=1 posS