HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

How is the formula for calculation in row/column major obtained?

Submitted by: @import:stackexchange-cs··
0
Viewed 0 times
calculationthemajorobtainedcolumnforhowrowformula

Problem

In my book, this formula is given for calculation of address of row major order's element $[I,J]$:

Address of $[I,J]$th element in row major order $= B + W[n(I-L_r)+ [J-L_c]]$

where B denotes base address, W denotes element size in bytes, n is the number of columns; $L_r$ is the first row number, $L_c$ is the first column number.

A similar formula is given for address in column major order.

I would like to know how this formula is obtained.

Solution

Row-major order stores the rows of the array one after another in memory. That is, the array

a d g j
b e h k
c f i l


is stored as

a d g j b e h k c f i l


To determine the address of an element in this list, we need to know how many elements come before it. For element $[I,J]$, this is the number of complete rows above row $I$ times the length of a row, which is $(I-L_r)\times n$, plus the number of elements before it in the current row, which is $J-L_c$.

Since the first element is at address $B$ and each element takes $W$ bytes, the addresses of the elements are $B$, $B+W$, $B+2W$, ... and, in general, if there are $k$ elements before you, your address is $B+kW$. For element $[I,J]$, we have calculated that $k=n(I-L_r)+(J-L_c)$.

For column-major, the argument is basically the same. If you understand the above, it should be easy to adapt it.

Code Snippets

a d g j
b e h k
c f i l
a d g j b e h k c f i l

Context

StackExchange Computer Science Q#96852, answer score: 5

Revisions (0)

No revisions yet.