CENG205 Ders4
CENG205 Ders4
Data structures
Lecture 4:
Lower/Upper Triangular Matrix
Band Matrix
Sparse Matrix
Lower Triangular Matrix
Lower Triangular Matrix
• Does the definition of a special data structure for triangular matrix provide any
benefits over a typical matrix in terms of memory and processing time?
• We can insert the items in a single dimensional array:
• ALT
a00 a10 a11 a20 a21 a22 a30 a31 a32 a33
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]
• Answer: i=1, there is one item in the 0th row, 2 items in the 1st row.
• i=2, there is one item in the 0th row, 2 items in the 1st row, 3 items in the 2nd row.
i(i +1)
= +( j)
2
Lower Triangular Matrix
void main(void){
int alt[MAX_SIZE];
int i, n;
scanf(“%d“, &n); //matrix size
readtriangularmatrix(alt,n);
for(i=0; i<=n*(n+1)/2-1; i++)
printf(“ %d“, alt[i]);
i=gettriangularmatrix(3,0,n);
if(i==-2)
printf(“\n invalid index\n“);
else if(i==-1)
printf(“\n access to the upper triangular\n“);
else
printf(“\n the position in ‘alt’ matrix: %d value: %d \n“, i, alt[i]);
Lower Triangular Matrix
void readtriangularmatrix(int alt[], int n) int gettriangularmatrix(int i, int j, int n){
{
int i, j, k; if(i<0 || i>=n || j<0 || j>=n){
if(n*(n+1)/2 > MAX_SIZE){ printf(“\n invalid index\n“);
printf(“\n invalid array size \n“); exit(-2);
exit(-1); }
} else if(i>=j) //valid index
else return (i+1)*i/2+j;
for(i=0; i<=n-1; i++){ else return -1; //outside of the triangular
k=(i+1)*i/2; //value is zero
for(j=0; j<=i; j++)
scanf(“%d“, &alt[k+j]);
}
}
Band Matrix
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11]
(a-1)a (b-1)b
= n(a+ b-1) - -
2 2
Band Matrix
Band Matrix
void main(void){
int band[MAX_SIZE];
int search[MAX_SIZE];
int i, n, a, b;
printf(“ n:“, &n); scanf(“%d“, &n);
printf(“ a:“, &a); scanf(“%d“, &a);
printf(“ b:“, &b); scanf(“%d“, &b);
buildbandmatrix(band,search,a,b);
printf(“\n“);
for(i=0; i<=a+b-2; i++)
printf(“ %d“, search[i]);
i=getbandmatrix(3,3,n,a,b,search);
if(i==2)
printf(“\n invalid index“);
else if(i==1)
printf(“\n item to be searched: 0“);
else
printf(“\n item to be searched: %d→%d“, i, band[i]);
Band Matrix
void buildbandmatrix(int band[], int search[], int n, int a, int b){
int i, k, itemnum;
if(n>0){
currentb=1;
for(i=0; i<a[0].col; i++)
for(j=1; j<=n; j++) //find the ones with col i in a
if(a[j].col==i){
b[currentb].row=a[j].col;
b[currentb].col=a[j].row;
b[currentb].value=a[j].value;
currentb++;
}
}
}