CSCE 3110 Data Structures & Algorithm Analysis: Rada Mihalcea
CSCE 3110 Data Structures & Algorithm Analysis: Rada Mihalcea
CSCE 3110 Data Structures & Algorithm Analysis: Rada Mihalcea
Rada Mihalcea
http://www.cs.unt.edu/~rada/CSCE3110
Arrays
Arrays
data structure
For each index, there is a value associated with
that index.
representation (possible)
implemented by using consecutive memory.
The Array ADT
Objects: A set of pairs <index, value> where for each value of index
there is a value from the set item. Index 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),(2,1),(2,2)} for two dimensions,
etc.
Methods:
for all A Array, i index, x item, j, size integer
Array Create(j, list) ::= return an array of j dimensions where list is a
j-tuple whose kth element is the size of the
kth dimension. Items are undefined.
Item Retrieve(A, i) ::= if (i index) return the item associated with
index value i in array A
else return error
Array Store(A, i, x) ::= if (i in index)
return an array that is identical to array
A except the new pair <i, x> has been
inserted else return error
Arrays in C
int list[5], *plist[5];
Notations:
list2 - a pointer to list2[0]
(list2 + i) - a pointer to list2[i] (&list2[i])
*(list2 + i) - list2[i]
Example
Example:
int one[] = {0, 1, 2, 3, 4}; //Goal: print out Address Contents
address and value
1228 0
void print1(int *ptr, int rows)
1230 1
{
1232 2
printf(“Address Contents\n”);
for (i=0; i < rows; i++) 1234 3
printf(“%8u%5d\n”, ptr+i, *(ptr+i)); 1236 4
printf(“\n”);
}
Other Data Structures
Based on Arrays
•Arrays:
•Basic data structure
•May store any type of elements
p( x ) a1 x e1 ... an x en
coef
2 1 1 10 3 1
exp
1000 0 4 3 2 0
0 1 2 3 4 5 6
Polynomial Addition (2) (cont’d)
#define MAX_DEGREE 101
typedef struct {
int exp; Running time?
float coef;
} polynomial_term;
polynomial_term terms[3*MAX_DEGREE];
Addition(int starta, int enda, int startb, int endb, int startc, int endc)
{
…
}
advantage: less space
disadvantage: longer code
Sparse Matrices
col1 col2 col3 col4 col5 col6
row0 15 0 0 22 0 15
row1
0 11 3 0 0 0
row2 0 0 0 6 0 0
row3 0 0 0 0 0 0
row4
91 0 0 0 0 0
row5 0 0 28 0 0 0
5*3 6*6
15/15 8/36
sparse matrix
data structure?
Sparse Matrix ADT
Objects: a set of triples, <row, column, value>, where row
and column are integers and form a unique combination, and
value comes from the set item.
Methods:
for all a, b Sparse_Matrix, x item, i, j, max_col,
max_row index