Row-wise vs column-wise traversal of matrix
Two common ways of traversing a matrix are row-major-order and column-major-order
Row Major Order: When matrix is accessed row by row.
Column Major Order: When matrix is accessed column by column.
Examples:
Input : mat[][] = {{1, 2, 3},
{4, 5, 6},
{7, 8, 9}}Output : Row-wise: 1 2 3 4 5 6 7 8 9
Col-wise : 1 4 7 2 5 8 3 6 9
In many problems (like Search in a Matrix), we can use any of the above two, so the question arises which one to use?
If we see according to time complexity, both lead to O(n2), but when it comes to cache level one of the orders access will be faster as compare to other one. It depends on the language we are using. Most of the languages including C, C++, Java, Python, C# and JavaScrtipt store matrix in row major form so while accessing the i+1th element after ith, most probably it will lead to a hit, which will further reduce the time of program.
The following codes are showing the time difference in row major and column major access.
#include <iostream>
#include <vector>
#include <ctime>
using namespace std;
void rowMajor(vector<vector<int>>& arr) {
int rows = arr.size();
int cols = arr[0].size();
// Accessing elements row-wise
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
arr[i][j]++;
}
}
}
void colMajor(vector<vector<int>>& arr) {
int rows = arr.size();
int cols = arr[0].size();
// Accessing elements column-wise
for (int j = 0; j < cols; j++) {
for (int i = 0; i < rows; i++) {
arr[i][j]++;
}
}
}
int main() {
int n = 1000; // Size of the matrix (n x n)
vector<vector<int>> arr(n, vector<int>(n, 0));
// Time taken by row-major order
clock_t t = clock();
rowMajor(arr);
t = clock() - t;
cout << "Row major access time: " << t / (double)CLOCKS_PER_SEC << " s\n";
// Time taken by column-major order
t = clock();
colMajor(arr);
t = clock() - t;
cout << "Column major access time: " << t / (double)CLOCKS_PER_SEC << " s\n";
return 0;
}
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#define MAX 1000 // Size of the matrix (MAX x MAX)
void rowMajor(int arr[MAX][MAX]) {
// Accessing elements row-wise
for (int i = 0; i < MAX; i++) {
for (int j = 0; j < MAX; j++) {
arr[i][j]++;
}
}
}
void colMajor(int arr[MAX][MAX]) {
// Accessing elements column-wise
for (int j = 0; j < MAX; j++) {
for (int i = 0; i < MAX; i++) {
arr[i][j]++;
}
}
}
int main() {
int arr[MAX][MAX] = {0}; // Initialize matrix with zeros
// Time taken by row-major order
clock_t t = clock();
rowMajor(arr);
t = clock() - t;
printf("Row major access time: %f s\n", (double)t / CLOCKS_PER_SEC);
// Time taken by column-major order
t = clock();
colMajor(arr);
t = clock() - t;
printf("Column major access time: %f s\n", (double)t / CLOCKS_PER_SEC);
return 0;
}
import java.time.Duration;
import java.time.Instant;
import java.util.*;
class GFG {
static void rowMajor(int[][] arr) {
int rows = arr.length;
int cols = arr[0].length;
// Accessing elements row-wise
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
arr[i][j]++;
}
}
}
static void colMajor(int[][] arr) {
int rows = arr.length;
int cols = arr[0].length;
// Accessing elements column-wise
for (int j = 0; j < cols; j++) {
for (int i = 0; i < rows; i++) {
arr[i][j]++;
}
}
}
public static void main(String[] args) {
int n = 1000; // Size of the matrix (n x n)
int[][] arr = new int[n][n];
// Time taken by row-major order
Instant start = Instant.now();
rowMajor(arr);
Instant end = Instant.now();
System.out.println("Row major access time: " + Duration.between(start, end));
// Time taken by column-major order
start = Instant.now();
colMajor(arr);
end = Instant.now();
System.out.println("Column major access time: " + Duration.between(start, end));
}
}
from time import perf_counter
def row_major(arr):
rows = len(arr)
cols = len(arr[0])
# Accessing elements row-wise
for i in range(rows):
for j in range(cols):
arr[i][j] += 1
def col_major(arr):
rows = len(arr)
cols = len(arr[0])
# Accessing elements column-wise
for j in range(cols):
for i in range(rows):
arr[i][j] += 1
if __name__ == '__main__':
n = 1000 # Size of the matrix (n x n)
arr = [[0] * n for _ in range(n)]
# Time taken by row-major order
t_start = perf_counter()
row_major(arr)
t_row = perf_counter() - t_start
print("Row major access time: {:.2f} s".format(t_row))
# Time taken by column-major order
t_start = perf_counter()
col_major(arr)
t_col = perf_counter() - t_start
print("Column major access time: {:.2f} s".format(t_col))
using System;
public class GFG {
public static void RowMajor(int[,] arr) {
int rows = arr.GetLength(0);
int cols = arr.GetLength(1);
// Accessing elements row-wise
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
arr[i, j]++;
}
}
}
public static void ColMajor(int[,] arr) {
int rows = arr.GetLength(0);
int cols = arr.GetLength(1);
// Accessing elements column-wise
for (int j = 0; j < cols; j++) {
for (int i = 0; i < rows; i++) {
arr[i, j]++;
}
}
}
public static void Main(string[] args) {
int n = 1000; // Size of the matrix (n x n)
int[,] arr = new int[n, n];
// Time taken by row-major order
var start = DateTime.UtcNow;
RowMajor(arr);
var end = DateTime.UtcNow;
TimeSpan spanR = end - start;
Console.WriteLine("Row major access time: " + spanR.TotalSeconds + " s");
// Time taken by column-major order
start = DateTime.UtcNow;
ColMajor(arr);
end = DateTime.UtcNow;
TimeSpan spanC = end - start;
Console.WriteLine("Column major access time: " + spanC.TotalSeconds + " s");
}
}
function rowMajor(arr) {
let rows = arr.length;
let cols = arr[0].length;
// Accessing elements row-wise
for (let i = 0; i < rows; i++) {
for (let j = 0; j < cols; j++) {
arr[i][j]++;
}
}
}
function colMajor(arr) {
let rows = arr.length;
let cols = arr[0].length;
// Accessing elements column-wise
for (let j = 0; j < cols; j++) {
for (let i = 0; i < rows; i++) {
arr[i][j]++;
}
}
}
// Driver code
let n = 1000; // Size of the matrix (n x n)
let arr = Array.from({ length: n }, () => Array(n).fill(0));
// Time taken by row-major order
let start = Date.now();
rowMajor(arr);
let end = Date.now();
console.log(`Row major access time: ${end - start} ms`);
// Time taken by column-major order
start = Date.now();
colMajor(arr);
end = Date.now();
console.log(`Column major access time: ${end - start} ms`);
Time Complexity: O(MAX*MAX)
Auxiliary Space: O(MAX*MAX)