Location of an element

Location of an element of a two-dimensional array
Row-major Order:
  • If Loc (A[i, j]) denotes the location in the memory of the element A[i][j] or Aij, then in row-major order –

Loc (A[i, j]) = Base (A) + (n (i - 1) + (j - 1)) * w;



  • Here Base (A) is starting or base address of the array A, n is the number of columns and w is the width of each cell, i.e, number bytes per cell.

Column-major Order:

In column-major order,

Loc (A[i, j]) = Base (A) + (m (j - 1) + (i - 1)) * w;

Here Base (A) is starting or base address of the array A, m is the number of rows and w is the cell width



Example:
Base address, Base (A) = 100, Size of the array = 5 × 6. If the type of array is integer then find Loc (A[4, 3]).
Solution:
(2 bytes for each integer cell in C/C++)
If the array is stored in row-major order:
Loc (A[4, 3]) = Base (A) + (n (i - 1) + (j - 1))* 2
= 100 + (6 × 3 + 2)* 2
= 100 + 40
= 140

If the array is stored in memory in column-major order:
Loc (A[4, 3]) = Base (A) + m (j - 1) + (i - 1)* 2
= 100 + (5 × 2 + 3)* 2
= 100 + 26
=126

No comments:

Post a Comment

Followers

About Me

Dhaka, Dhaka, Bangladesh
..