0% found this document useful (0 votes)
16 views38 pages

Module+2+Part+1

Uploaded by

mranonymous29823
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views38 pages

Module+2+Part+1

Uploaded by

mranonymous29823
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 38

Module 2

1
Syllabus
Arrays and Matrices: Arrays, Matrices, Special matrices, Sparse matrices.
Stacks: The abstract data types, Array Representation, Linked
Representation, Applications - Parenthesis Matching & Towers of Hanoi.

21ECE7034 - Data Stucture using C++ 2


Arrays and Matrices

3
ARRAYS
The Abstract Data Type
• Each instance of an array is a set of pairs of the form (index, value).
• No two pairs in this set have the same index.
• Operations performed on the array:
– Get an element—Gets the value of the pair that has a given index.
– Set an element—Adds a pair of the form (index, value) to the set, and
if a pair with the same index already exists, deletes the old pair.

21ECE7034 - Data Stucture using C++ 4


Abstract Data Type Specification of an array
AbstractDataType array
{
instances
set of (index, value) pairs, no two pairs have the same index
operations
get(index) : return the value of the pair with this index
set(index, value): add this pair to set of pairs, overwrite existing pair (if any) with
the same index
}
21ECE7034 - Data Stucture using C++ 5
Example
The high temperature (in degrees Fahrenheit) for each day

hightemp = {(Sunday, 82), (Monday, 79), (Tuesday, 85), (Wednesday, 92),


(Thursday, 88), (Friday, 89), (Saturday, 91)}

Each pair of the array is composed of an index (day of week) and a value
(the high temperature for that day). The name of the array is hightemp.
set( Monday, 83) get( Friday )

21ECE7034 - Data Stucture using C++ 6


An alternative array to represent the daily high temperature is

hightemp = {(0,82), (1,79), (2,85), (3,92), (4, 88), (5, 89), (6,91)}

In this array the index is a number rather than the name of the day.
The numbers (0, 1, 2, ..) replace the names of the days of the week

21ECE7034 - Data Stucture using C++ 7


Indexing a C++ Array
An array is a standard data structure in C++.
The index (also called subscript) of an array in C++ must be of the form
[i1][i2][i3] ….. [ik]
where each ij is a nonnegative integer.

21ECE7034 - Data Stucture using C++ 8


1D Array Representation In C++
Memory
a b c d

start

• 1-dimensional array x = [a, b, c, d]


• map into contiguous memory locations
• location(x[i]) = start + i
Space Overhead
Memory
a b c d

start

space overhead = 4 bytes for start


2D Arrays

The elements of a 2-dimensional array a declared as:


int a[3][4];

a[0][0] a[0][1] a[0][2] a[0][3]


a[1][0] a[1][1] a[1][2] a[1][3]
a[2][0] a[2][1] a[2][2] a[2][3]
Rows of a 2D Array

a[0][0] a[0][1] a[0][2] a[0][3] row 0


a[1][0] a[1][1] a[1][2] a[1][3] row 1
a[2][0] a[2][1] a[2][2] a[2][3] row 2
Columns of a 2D Array

a[0][0] a[0][1] a[0][2] a[0][3]


a[1][0] a[1][1] a[1][2] a[1][3]
a[2][0] a[2][1] a[2][2] a[2][3]
column 0 column 1 column 2 column 3
Row- and Column- Major Mappings
• Some applications of arrays require us to arrange the array elements
into a serial or one-dimensional order.
• For example, the elements of an array can be output or input only one
element at a time.
• Therefore, we must decide on the order in which the array elements are
output or input.

21ECE7034 - Data Stucture using C++ 14


Let n be the number of elements in a k-dimensional array.
The serialization of the array is done using a mapping function, which
maps the array index [i1][i2][i3] ….. [ik] into a number map(i1 , i2 , i3 … ik) in
the range [0, n — 1] such that array element with index [i1][i2][i3] ….. [ik]
is mapped to position map(i1 , i2 , i3 … ik) in the serial order.

21ECE7034 - Data Stucture using C++ 15


int a [3][4];

[0][0] [0][1] [0][2] [0][3]


[1][0] [1][1] [1][2] [1][3]
[2][0] [2][1] [2][2] [2][3]

Row-major mapping Column-major mapping


0 1 2 3
0 3 6 9
4 5 6 7
1 4 7 10
8 9 10 11
2 5 8 11

map(i1 , i2) = i1u2 + i2

21ECE7034 - D t Stucture using C++ 16


Array of Arrays Representation
[0] [1] [2] [3] [4]

x[0]
x[1]

x[2]

int x[3][5];
3 separate 1-dimensional arrays
One block is large enough for three pointers and each of the remaining blocks is
large enough for 5 ints. At 4 bytes per pointer and int, a total of 72 bytes is used.
Row-Major Mapping
•Example 3 x 4 array:
abcd
efgh
i jkl
•Convert into 1D array y by collecting elements by rows.
•Within a row elements are collected from left to right.
•Rows are collected from top to bottom.
•y[] = {a, b, c, d, e, f, g, h, i, j, k, l}
row 0 row 1 row 2 … row i
Locating Element x[i][j]
0 c 2c 3c ic
row 0 row 1 row 2 … row i

•assume x has r rows and c columns


•each row has c elements
•i rows to the left of row i
•so ic elements to the left of x[i][0]
•so x[i][j] is mapped to position
ic + j of the 1D array
Disadvantage
Need contiguous memory of size rc.
Column-Major Mapping
abcd
efgh
i jkl
•Convert into 1D array y by collecting elements by
columns.
•y = {a, e, i, b, f, j, c, g, k, d, h, l}
Irregular Two-Dimensional Arrays
int main(void)
{
int numberOfRows = 5;
// define the length of each of the five rows
int length[5] = {6, 3, 4, 2, 7};
// declare a two-dimensional array variable and
allocate the desired number of rovs
int **irregularArray = new int* [numberOfRows] ;
// now allocate space for the elements in each row
for (int i = 0; i < numberOfRows; i++)
irregularArray[i] = new int [length[i]];
22
// use the array like any regular array
irregularArray[2] [3] = 5;
irregularArray [4][6] = irregularArray[2][3] + 2;
irregularArray [1] [1] = 3;
// output selected elements
cout << irregularArray[2] [3] << endl;
cout << irregulardArray [4] [6] << endl;
cout << irregularArray[1][1] << endl;
return 0;
}

23
MATRICES
Definitions and Operations
• An mxn matrix is a table with m rows and n columns.
• m and n are the dimensions of the matrix.
• Matrices are used to organize data.

21ECE7034 - Data Stucture using C++ 24


Matrix
Table of values. Has rows and columns, but numbering
begins at 1 rather than 0.
a b c d row 1
e f g h row 2
i jkl row 3
•Use notation M(i,j) rather than M[i][j].
•May use a 2D array to represent a matrix.
Shortcomings of Using A 2D Array For A Matrix

•Indexes are off by 1.


•C++ arrays do not support matrix operations such as
add, transpose, multiply, and so on.
–Suppose that x and y are 2D arrays. Can’t do x + y, x –y, x *
y, etc. in C++.
•Develop a class matrix for object-oriented support of
all matrix operations.
The Class matrix
A rows x cols matrix M, all of whose elements are integer, may be
represented as a two-dimensional integer array
int x[rows] [cols];
with M(i,j) being stored as x[i-1][j-1]. This representation requires the
user to write applications using array indexes that differ from matrix
indexes by 1.

21ECE7034 - Data Stucture using C++ 27


Header for the class matrix
template<class T>
class matrix
{
friend ostream& operator<<(ostream&, const matrix<T>&) ;
public:
matrix(int theRows = 0, int theColumns = 0);
matrix(const matrix<T>&) ;
~matrix() {delete [] element;}
int rows() const {return theRows;}
int columns() const {return theColumns;}
T& operator()(int i, int j) const;

21ECE7034 - Data Stucture using C++ 28


matrix<T>& operator=(const matrix<T>&) ;
matrix<T> operator+() const; // unary +
matrix<T> operator+(const matrix<T>&) const;
matrix<T> operator-() const; // unary minus
matrix<T> operator-(const matrix<T>&) const;
matrix<T> operator*(const matrix<T>&) const;
matrix<T>& operator+=(const T&) ;
private:
int theRows, // number of rows in matrix
theColumns; // number of columns in matrix
T *element; // element array
};
21ECE7034 - Data Stucture using C++ 29
Constructor for matrix
template<class T>
matrix<T>::matrix(int theRows, int theColumns)
{// matrix constructor. ,
// validate theRows and theColumns
if (theRows < 0 || theColumns < 0)
throw illegalParameterValue("Rows and columns must be >= 0");
if ((theRows == 0 || theColumns == 0)&& (theRows != 0 || theColumns !=
0))
throw illegalParameterValue
("Either both or neither rows and columns should be zero");
// create the matrix
this->theRows = theRows;
this->theColumns = theColumns;
element = new T [theRows * theColumns] ;
21ECE7034 - Data Stucture using C++ 30
}
Copy Constructor for matrix
template<class T>
matrix<T>::matrix(const matrix<T>& m)
{// Copy constructor for matrices.
// create matrix
theRows = m.theRows;
theColumns = mo.theColumns;
element = new T [theRows * theColumns] ;
// copy each element of m
copy (m.element, m.element + theRows * theColumns,element};
}

21ECE7034 - Data Stucture using C++ 31


Overloading the = operator for matrix
template<class T>
matrix<T>& matrix<T>::operator=(const matrix<T>& m)
{// Assignment. (*this) = m.
if (this != &m)
{// not copying to self
delete [] element;
theRows = m.theRows;
theColumns = m.theColumns;
element = new T [theRows * theColumns] ;
// copy each element
copy (m.element, m.element + theRows * theColumns,element);
}
return *this;
} 21ECE7034 - Data Stucture using C++ 32
Overloading the ( ) operator for matrix
template<class T>
T& matrix<T>::operator() (int i, int j) const
{// Return a reference to element (i,j).
if (i < 1|| i > theRows || 4 <1 || j > theColumns)
throw matrixIndexOutOfBounds();
return element[(i - 1) * theColumns + j - 1];
}

21ECE7034 - Data Stucture using C++ 33


Matrix Addition
template<class T>
matrix<T> matrix<T>::operator+(const matrix<T>& m) const
{// Return w = (*this) + m.
if (theRows != m.theRows || theColumns != m.theColumns)
throw matrixSizeMismatch() ;
// create result matrix w
matrix<T> w(theRows, theColumns) ;
for (int i= 0; i < theRows * theColumns; i++)
w.element [i] = element[i] + m.element [i];
return w;
}

21ECE7034 - Data Stucture using C++ 34


Matrix Multiplication
template<class T>
matrix<T> matrix<T>::operator*(const matrix<T>& m) const
{// matrix multiply. Return w = (*this) + m.
if (theColumns != m.theRows)
throw matrixSizeMismatch();
matrix<T> w(theRows, m.theColumns); // result matrix
// define cursors for *this, m, and w
// and initialize to location of (1,1) element
int ct = 0, cm = 0, cw = 0;

21ECE7034 - Data Stucture using C++ 35


// compute w(i,j) for all i and j
for (int i = 1; i <= theRows; i++)
{// compute row i of result
for (int j = 1; j <= m.theColumns; j++)
{ // compute first term of w(i,j)
T sum = element(ct) * m.element [cm];
// add in remaining terms
for (int k = 2; k <= theColumns; k++)
{
ct++; // next term in row i of *this
cm += m.theColumns; // next in column j of m
sum += element(ct] * m.element [cm];
}
21ECE7034 - Data Stucture using C++ 36
w.element(cw++] = sum; // save w(i,j)
// reset to start of row and next column
ct -= theColumns - 1;
cm = j;
}
// reset to start of next row and first column
ct += theColumns; ;
cm = 0;
}
return w;
}

21ECE7034 - Data Stucture using C++ 37


Complexity
● Constructor and Destructor Complexity:
○ Complexity is O(1) when T is a primitive data type (e.g., int, double).
○ Complexity becomes O(theRows * theColumns) when T is a user-defined
data type, as the constructor (or destructor) is called for each position in the
array during creation (or deletion).
● Copy Constructor and Add Method Complexity:
○ Complexity is O(theRows * theColumns), assuming that copying a matrix
term and adding two matrix terms are both O(1) operations.
● Matrix Multiplication Complexity:
○ Complexity is O(theRows * theColumns * m.theColumns), based on the
matrix dimensions involved in the multiplication process.

21ECE7034 - Data Stucture using C++ 38

You might also like