Arrays and dynamic arrays · Θ(rows · cols)

Matrix traversal

Row-major vs column-major order with the address mapping, stride per visit and jagged rows.

The full explanation, derivation and practice are in the lesson Multidimensional and jagged arrays.

Implementation

The code the visualizer highlights, in four languages. Each is tested against one shared set of cases and a randomized comparison with the language's built-in equivalent.

namespace Bekadan.Dsa.Examples.Arrays;
 
/// <summary>
/// Reading a two-dimensional array in row order, in column order, and as a
/// jagged array of rows. A rectangular matrix is stored row-major in one block
/// (as <c>int[,]</c> is): element (r, c) sits at offset r * cols + c. Every
/// traversal reads each element once: O(rows * cols) time, O(1) extra space
/// besides the returned list.
/// </summary>
public static class MatrixTraversal
{
    /// <summary>Row order over row-major storage: consecutive reads are adjacent in memory.</summary>
    public static List<int> RowMajor(ReadOnlySpan<int> flat, int rows, int cols)
    {
        var order = new List<int>(rows * cols);
        for (int r = 0; r < rows; r++)
        {
            for (int c = 0; c < cols; c++)
            {
                int offset = r * cols + c;
                order.Add(flat[offset]);
            }
        }
        return order;
    }
 
    /// <summary>Column order over the same row-major storage: each read jumps cols elements ahead.</summary>
    public static List<int> ColumnMajor(ReadOnlySpan<int> flat, int rows, int cols)
    {
        var order = new List<int>(rows * cols);
        for (int c = 0; c < cols; c++)
        {
            for (int r = 0; r < rows; r++)
            {
                int offset = r * cols + c; // same formula, different loop order
                order.Add(flat[offset]);
            }
        }
        return order;
    }
 
    /// <summary>A jagged array: each rows[r] is a reference to its own array, of any length.</summary>
    public static List<int> Jagged(int[][] rows)
    {
        var order = new List<int>();
        for (int r = 0; r < rows.Length; r++)
        {
            int[] row = rows[r]; // read the reference first
            for (int c = 0; c < row.Length; c++)
            {
                order.Add(row[c]);
            }
        }
        return order;
    }
 
    /// <summary>Byte address of element (r, c) in a row-major block starting at baseAddress.</summary>
    public static long AddressOf(long baseAddress, int cols, int elementSize, int r, int c) =>
        baseAddress + (long)(r * cols + c) * elementSize;
 
    /// <summary>
    /// Copies an int[,] into a flat buffer byte for byte. The result is in row-major
    /// order because that is how the runtime lays out a rectangular array.
    /// </summary>
    public static int[] ToRowMajorBuffer(int[,] matrix)
    {
        var flat = new int[matrix.Length];
        Buffer.BlockCopy(matrix, 0, flat, 0, matrix.Length * sizeof(int));
        return flat;
    }
}

Tested on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples/Arrays/MatrixTraversal.cs

"""Reading a two-dimensional array in row order, in column order, and as a
jagged list of rows.
 
Core Python has no rectangular 2D array: a "matrix" is a list of row lists,
each row a separate object. To show the address arithmetic of a real
rectangular array, the first two functions read a flat list in row-major
order, where element (r, c) sits at offset r * cols + c. Every traversal reads
each element once: O(rows * cols) time, O(1) extra space besides the result.
"""
 
from collections.abc import Sequence
 
 
def row_major(flat: Sequence[int], rows: int, cols: int) -> list[int]:
    """Row order over row-major storage: consecutive reads are adjacent."""
    order: list[int] = []
    for r in range(rows):
        for c in range(cols):
            offset = r * cols + c
            order.append(flat[offset])
    return order
 
 
def column_major(flat: Sequence[int], rows: int, cols: int) -> list[int]:
    """Column order over the same row-major storage: each read jumps cols elements."""
    order: list[int] = []
    for c in range(cols):
        for r in range(rows):
            offset = r * cols + c  # same formula, different loop order
            order.append(flat[offset])
    return order
 
 
def jagged(rows: Sequence[Sequence[int]]) -> list[int]:
    """A list of rows: each rows[r] is a reference to its own list, of any length."""
    order: list[int] = []
    for r in range(len(rows)):
        row = rows[r]  # read the reference first
        for c in range(len(row)):
            order.append(row[c])
    return order
 
 
def address_of(base: int, cols: int, element_size: int, r: int, c: int) -> int:
    """Byte address of element (r, c) in a row-major block starting at base."""
    return base + (r * cols + c) * element_size

Tested on CPython 3.14.0 · examples/python/dsa_examples/matrix_traversal.py

package dev.bekadan.dsa.arrays;
 
/**
 * Reading a two-dimensional array in row order, in column order, and as a
 * jagged array of rows. Java has no rectangular array type: {@code int[][]}
 * is an array of references to separate row arrays. To show the address
 * arithmetic of a rectangular block, the first two methods read a flat
 * row-major buffer, where element (r, c) sits at offset r * cols + c. Every
 * traversal reads each element once: O(rows * cols) time, O(1) extra space
 * besides the result.
 */
public final class MatrixTraversal {
    private MatrixTraversal() {
    }
 
    /** Row order over row-major storage: consecutive reads are adjacent in memory. */
    public static int[] rowMajor(int[] flat, int rows, int cols) {
        int[] order = new int[rows * cols];
        int k = 0;
        for (int r = 0; r < rows; r++) {
            for (int c = 0; c < cols; c++) {
                int offset = r * cols + c;
                order[k++] = flat[offset];
            }
        }
        return order;
    }
 
    /** Column order over the same row-major storage: each read jumps cols elements ahead. */
    public static int[] columnMajor(int[] flat, int rows, int cols) {
        int[] order = new int[rows * cols];
        int k = 0;
        for (int c = 0; c < cols; c++) {
            for (int r = 0; r < rows; r++) {
                int offset = r * cols + c; // same formula, different loop order
                order[k++] = flat[offset];
            }
        }
        return order;
    }
 
    /** An array of arrays: each rows[r] is a reference to its own array, of any length. */
    public static int[] jagged(int[][] rows) {
        int total = 0;
        for (int[] row : rows) {
            total += row.length;
        }
        int[] order = new int[total];
        int k = 0;
        for (int r = 0; r < rows.length; r++) {
            int[] row = rows[r]; // read the reference first
            for (int c = 0; c < row.length; c++) {
                order[k++] = row[c];
            }
        }
        return order;
    }
 
    /** Byte address of element (r, c) in a row-major block starting at base. */
    public static long addressOf(long base, int cols, int elementSize, int r, int c) {
        return base + (long) (r * cols + c) * elementSize;
    }
}

Tested on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/main/java/dev/bekadan/dsa/arrays/MatrixTraversal.java

#pragma once
 
#include <cstddef>
#include <cstdint>
#include <span>
#include <vector>
 
namespace bekadan::dsa {
 
// Reading a two-dimensional array in row order, in column order, and as a
// jagged vector of rows. A rectangular matrix is stored row-major in one block
// (as int[R][C] is): element (r, c) sits at offset r * cols + c. Every
// traversal reads each element once: O(rows * cols) time, O(1) extra space
// besides the result.
 
// Row order over row-major storage: consecutive reads are adjacent in memory.
inline std::vector<int> row_major(std::span<const int> flat, std::size_t rows, std::size_t cols) {
    std::vector<int> order;
    order.reserve(rows * cols);
    for (std::size_t r = 0; r < rows; ++r) {
        for (std::size_t c = 0; c < cols; ++c) {
            const std::size_t offset = r * cols + c;
            order.push_back(flat[offset]);
        }
    }
    return order;
}
 
// Column order over the same row-major storage: each read jumps cols elements ahead.
inline std::vector<int> column_major(std::span<const int> flat, std::size_t rows, std::size_t cols) {
    std::vector<int> order;
    order.reserve(rows * cols);
    for (std::size_t c = 0; c < cols; ++c) {
        for (std::size_t r = 0; r < rows; ++r) {
            const std::size_t offset = r * cols + c;  // same formula, different loop order
            order.push_back(flat[offset]);
        }
    }
    return order;
}
 
// A vector of vectors: each row owns a separate heap block, of any length.
inline std::vector<int> jagged(const std::vector<std::vector<int>>& rows) {
    std::vector<int> order;
    for (std::size_t r = 0; r < rows.size(); ++r) {
        const std::vector<int>& row = rows[r];  // find the row block first
        for (std::size_t c = 0; c < row.size(); ++c) {
            order.push_back(row[c]);
        }
    }
    return order;
}
 
// Byte address of element (r, c) in a row-major block starting at base.
constexpr std::uint64_t address_of(std::uint64_t base, std::size_t cols, std::size_t element_size, std::size_t r, std::size_t c) {
    return base + (r * cols + c) * element_size;
}
 
}  // namespace bekadan::dsa

Tested on C++23, GCC 15.3 (libstdc++) · examples/cpp/include/bekadan/dsa/matrix_traversal.hpp