JMU
Segmented (or Packed) Arrays
A Programming Pattern


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu


Motivation
Review
Thinking About the Problem

Concatenating the Two Arrays

javaexamples/programmingpatterns/segmentedarrays/SegmentedArrays.java (Fragment: concatenate2)
            int n = 4;
            for (int i = 0; i < n; ++i) {
                concatenated[i]   = height[i];
            }

            for (int i = 0; i < n; ++i) {
                concatenated[n + i] = weight[i];
            }
        
Thinking About the Problem (cont.)

Conceptualizing the Concatenated Array

images/SegmentedArrays_Concatenated.svg
Thinking About the Problem (cont.)

Interleaving the Two Arrays

javaexamples/programmingpatterns/segmentedarrays/SegmentedArrays.java (Fragment: interleave)
            int n = 4;
            for (int i = 0; i < n; ++i) {
                interleaved[2 * i]     = height[i];
                interleaved[2 * i + 1] = weight[i];
            }
        
Thinking About the Problem (cont.)

Conceptualizing the Interleaved Array

images/SegmentedArrays_PersonArray.svg
The Pattern
An Example
An Example (cont.)