Lecture 4-Arrays
Lecture 4-Arrays
Lecture 4-Arrays
Algorithms
Arrays
Arrays
• data structure
• For each index, there is a value
associated with that index.
• Representation
• implemented by using consecutive
memory.
Arrays
One Dimensional Array:
int A[10];
int A[10][25];
3
The Array as ADT
Objects: A set of pairs <index, value> where for each value of
index there is a value from the set item.
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] i.e (&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
{
printf(“Address Contents\n”);
1232 2
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
•Note
• Arrays:
Polynomials A(X)=3X20+2X5+4,
B(X)=X4+10X3+3X2+1
6 2 3 8 -3 18 0 0 23
0 1 2 3 0 1 2 3 4
Index represents
exponents
Polynomial ADT
This is why arrays aren’t good to represent
polynomials:
6 2 0 0 -3 0 ………… 0 16
WASTE OF SPACE!
Polynomial ADT
Advantages of using an Array:
21
Polynomial ADT Operations
Additions
24
Polynomial Addition (2)
• Use one global array to store all
polynomials
A(X)=2X1000+1
B(X)=X4+10X3+3X2+1
Start_a finish_a start_b finishb avail
coef 2 1 1 10 3 1
exp 1000 0 4 3 2 0
0 1 2 3 4 5 6
2nd Representation As Arrays
In C:
typedef struct {
int coeff, exp;
} polynomial;
polynomial terms[MAX_TERMS];
int avail = 0;
26
Polynomial ADT
Methods:
functions:
for all poly, poly1, poly2 Polynomial, coef Coefficients, expon Exponents
29
Matrix Representation
30
Operations: Transpose & Add
c transpose(a) // a: m x n matrix
for (i=0; i<rowA; i++) // O(m)
for (j=0; j<colA; j++) // O(n)
c[j][i]=a[i][j];
Running time = O(mn)
c add(a, b) // a, b: m x n matrices
for (i=0; i<rowA; i++) // O(m)
for (j=0; j<colA; j++) // O(n)
c[i][j]=a[i][j]+b[i][j];
E.g.
Sparse Matrices
An example sparse matrix:
15 0 0 22 0 -15
0 11 3 0 0 0
A= 0 0 0 -6 0 0
0 0 0 0 0 0
91 0 0 0 0 0
0 0 28 0 0 0
A lot of “zero” entries.
Thus large memory space is wasted.
typedef struct {
int col, row, value;
} term;
term a[MAX_TERMS];
36
Operations: Transpose
c transpose(a) // a: m x n matrix
//Algorithm 1:
for each row i {
take element (i, j, value) and
store it as (j, i, value).
} valuae
row col row col
[ ]
15 0 0 22
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,
Methods:
for all a, b Sparse_Matrix, x item, i, j, max_col,
max_row index