Module+2+Part+1
Module+2+Part+1
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.
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.
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 )
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
start
start
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
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.