3 Arrays
3 Arrays
Array overview
For 1D array:
Let ARR[lb,ub] be an array where lb and ub are values of lowest index and
largest index .
Note: To access any element in array constant time is needed because other
elements scanning is not required.
2D array (Matrices)
OR
name_array[rsubscript, csubscript] like ARR[i,j] used in PASCAL
Memory representation of 2D Array
Two ways: Row major order and column major order
Row major order:
Let w be number of bytes per element, lbc is lower bound of columns and lbr is
lower bound of rows.
Address of element of ith row and jth column of an array of mxn size is given by,
loc(a[i] [j]) = base(a) + w * [n*(i - lbr) + (j - lbc)]
loc(a[i] [j]) = base(a) + w * [n* i + j ] In C/C++
00 01 02 03
Let base(a) = 2013
10 11 12 13
loc[2][1] = 2013 + 4* [ 4 * 2 + 1]
20 21 22 23 = 2013 + 4 * 9
30 31 32 33 = 2049
40 41 42 43
double percentage[50];
If this array percentage is stored in memory starting from address 3000.
then what will be the address of percentage[20] element.
02/08/2025 7
Operations on arrays
Time complexity in best case =O(1) (When k is N-1 i.e. delete last element)
Time complexity in worst case =O(n) (When k is 0 i.e. delete first element)
Sparse Matrix
Most of the elements are zero
As many of its elements are zero, we can save space by storing only non-zero elements.
Example:
0 2 0 0 Number of non-zero entries = 3
Number of zero entries = 13
0 1 0 0
Elements to be stored = 16
3 0 0 0
0 0 0 0
Number of
non-zero
Number of Number of entries
rows(m) cols(n)
4 4 3
1 2 2
Only non-zero elements:
2 2 1
<row, col, element>
3 1 3
Elements to be stored = 12
7 6 16
Elements = 51
Let see one more example – 1 2 5
Number of non-zero entries = 16 1 4 9
Number of zero entries = 26 2 2 45
Elements to be stored = 42
2 5 8
0 5 0 9 0 0 3 1 8
0 45 0 0 8 0 3 6 9
8 0 0 0 0 9 4 1 67
67 0 0 5 5 0 4 4 5
0 5 0 30 0 0 4 5 5
8 0 0 8 0 0 5 2 5
8 0 0 7 0 31 5 4 30
6 1 8
6 4 8
Number of non-zero entries = k
7 1 8
Number of rows =m
Number of columns =n 7 4 7
Condition: 3(k+1) < m*n 7 6 31
Advantages of Sparse Matrices
• Two advantages:
– Storage: There are lesser non-zero elements than zeros
and thus lesser memory can be used to store only non-
zero elements.
– Computing time: Computing time can be saved by logically
designing a data structure traversing only non-zero
elements.
Problem
Is there any space benefit after converting below matrix in triplet
form? If YES then represent it.
5 6 7
1 5 3
2 2 9
2 6 2
3 3 1
3 4 8
YES 4 5 4
Here 5 1 3
Number of non-zero entries = k=7
Number of rows = m=5
Number of columns = n=6
Condition: 3(k+1) < m*n=3(7+1)<30