Data Structures, Algorithms, & Applications in Java
Chapter 8, Exercise 9
- (a)
-
Java uses the array of arrays representation. When
m = 10
and n = 2, we have
1 one-dimensional array of size
10 (the elements of this array are Java references)
and
10 one-dimensional arrays of size
2 (the elements of these arrays are integers).
Each of the
11 one-dimensional arrays has a
length field which is an integer.
So, the total space is
1 x 10 x 4 + 10 x 2 x 4 + 11 x 4 = 164 bytes.
When a single one-dimensional array is used (i.e., when the elements
are mapped using (say) row-major order), the space required
is 10 x 2 x 4 + 4 = 84 bytes.
The ratio is 164 / 84 = 1.95.
For general m and n,
the array of arrays representation requires
1 x m x 4 + m x n x 4 + (m + 1) x 4 = 4mn + 8m + 4
bytes.
The one-dimensional mapping takes
m x n x 4 + 4 = 4mn + 4
bytes.
- (b)
-
The ratio is
(4mn + 8m + 4) / (4mn + 4) = 1 + 8m/(4mn + 4).
This is maximum when n is least.
For a two-dimensional array, n >= 2.
So, the maximum value of the ratio is
1 + 8m/(8m + 4). This approaches 2
as m gets large.